c++中整数数组的减法

subtractings arrays of ints in c++

本文关键字:数组 整数 c++      更新时间:2023-10-16

我有两个大小为40的整数数组。它们是HugeInteger类的对象。我需要减去它们。我的代码是

HugeInteger HugeInteger::subtract(HugeInteger other)
{
    int diff;
    HugeInteger result;
    for (int i=0; i<MAXDIGIT; i++)
    {
        diff=this ->myArray[i]-other.myArray[i];
        if (other.myArray[i] < this -> myArray[i])
        {
            result.myArray[i]=diff;
        }
        else
        {
            result.myArray[i]=other.myArray[i]-this->myArray[i];
        }
    }
    return result;
}

问题是上面的代码没有给我正确的答案。我用计算器检查过了,有些数字是对的,有些是错的。我想问题可能是我如何处理借位如果减法会导致一个数字是负的。有人能帮帮我吗?我已经想了8个小时了

你说的是"借用",但代码中没有。

代码,

HugeInteger HugeInteger::subtract(HugeInteger other)
{
    int diff;
    HugeInteger result;
    for (int i=0; i<MAXDIGIT; i++)
    {
        diff=this ->myArray[i]-other.myArray[i];
        if (other.myArray[i] < this -> myArray[i])
        {
            result.myArray[i]=diff;
        }
        else
        {
            result.myArray[i]=other.myArray[i]-this->myArray[i];
        }
    }
    return result;
}

似乎计算每个数字差的绝对值。


一种简单的减法方法是计算你要减法的数字的N的补数,然后加,其中N是你的数字系统的基数,忽略最高有效数字的进位。

。,要计算55522 - 12345,首先计算99999 - 12345 = 87654,这是基数为10的9的补码,然后加1,得到87655,10的补码,然后加上55522 + 87655 = 143177,忽略进位,得到43177。

检查:43177 + 12345 = 55522,hurray,它工作了

我认为在for loop中你应该使用这个

 if ((other.myArray[i]) < (this -> myArray[i]))
 {
     result.myArray[i] = this ->myArray[i] - other.myArray[i];
 }
 else
 {
    result.myArray[i] = other.myArray[i] - this->myArray[i];
 }

这将克服diff变量的size问题。请检查…

是,在完成substract函数代码后检查result对象是否活。这也可能导致问题。如果是,在函数中创建HugeInteger类的对象,然后创建return相同的

希望对你有帮助