BigInt乘法w/int数组
BigInt Multiplication w/ int arrays
我正在用C++制作一个BigInt
类作为练习。我目前正在研究乘法功能。我的BigInt
表示为一个固定长度(非常大)的int[]
,每个条目都是输入数字的一位数字。
因此,BigInt = 324
将导致[0,0,0,..,3,2,4]
。
我目前正在尝试使用以下代码进行乘法运算:
// multiplication
BigInt BigInt::operator*(BigInt const& other) const {
BigInt a = *this;
BigInt b = other;
cout << a << b << endl;
BigInt product = 0;
for(int i = 0; i < arraySize; i++){
int carry = 0;
for(int j = 0; j < arraySize; j++){
product.digits[arraySize - (j + i)] += (carry + (a.digits[j] * b.digits[i]));
carry = (product.digits[arraySize - (j + i)] / 10);
product.digits[arraySize - (j + i)] = (product.digits[arraySize - (j + i)] % 10);
}
product.digits[arraySize - i] += carry;
}
return product;
}
我的答案一直返回0。例如,2 * 2 = 0
。
不确定这是否会修复您的程序,但您有Undefined Behavior
,因为它:
product.digits[arraySize - (j + i)]
当i + j > arraySize
时,这个索引arraySize - (j + i)
变为负值,这显然会发生在循环中。
基本上,当两个数字乘以n个数字时,结果可能宽至2n个数字。由于您将所有数字编码在固定长度的arraySize
上,因此必须采取措施避免越界。
if(i+j) <= arraySize
可以做一个简单的测试,或者通过改变第二个循环:
for(int j = 0; j < arraySize - i; j++)
或者,最好使用std::vector
作为BigInt的内部表示。它可以动态调整大小以预先适应您的结果。
目前还不能完全确定这是否会完全修复您的代码,但在继续调试之前,必须先修复它。删除UB后会更容易。在这里,我赞同@Dúthomhas的注意,即您对数组的索引似乎明显不规则。。。结果从右到左,输入从左到右。。。
相关文章:
- 按字符值访问int数组
- 将 int 数组转换为 std::vector<int*>
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 整数区间(或 int 数组)中每个数字的出现次数
- Int 数组到C++容器
- C++ 未初始化的本地(非全局)int 数组中的元素类型到底是什么?
- 如何检测将文本文件读入 int 数组的新行
- C++快速将 int 数组内容转储到文本文件中
- <string> 如何在使用 SWIG 时将 int 数组和 List 作为参数传递给 C# C++
- 如何制作不允许重复值的 C++ int 数组循环?
- 如何将逗号分隔的文件读取为 2D int 数组?
- int 数组,但索引是字符?
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 将 int 数组转换为带有小数C++的双精度数组
- 将双精度值分配给 int 数组时的类型转换
- 已编辑 我如何将其拆分为 char 和 int 数组
- 从 C++ 中的 int ** 数组访问元素
- C++程序无法分配 int 数组?
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 如何通过头文件中的函数初始化 const int 数组?