c++中整数数组的减法
subtractings arrays of ints in c++
我有两个大小为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
相同的
希望对你有帮助
相关文章:
- C++使用整数的压缩数组初始化对象
- 在一定长度后从数组中打印时缺少整数
- 是否基于数组B整数打印数组A中的整数
- 检查TCHAR数组输入是否为带符号整数C++
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 从二进制文件中读取整数数组
- 整数区间(或 int 数组)中每个数字的出现次数
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- C++数组输入不接受一定数量的整数
- 从两个 4x64 位整数数组中获取取模
- 如何计算数组整数的总可能组合
- 2D 字符串数组 C++:整数串联成字符串
- 将数组整数2除以偶数和
- 将2d数组整数数据从c++发送到qml