gpt4 book ai didi

c++ - Bigint *运算符

转载 作者:行者123 更新时间:2023-11-28 07:30:52 26 4
gpt4 key购买 nike

我正在做一个 bigint 项目,我很困惑为什么我的乘法运算符在测试用例上不能正常工作。

我排除了 .h 文件,因为它可能没有必要。

bigint.cpp:

// Definition of multiplication operator
BigInt BigInt::operator*(BigInt addend2)
{
BigInt product;
short int first, // a block of 1st addend (this object)
second, // a block of 2nd addend (addend2)
result, // a block in their sum
carry = 0; // the carry in adding two blocks

list<short int>::reverse_iterator // to iterate right to left
it1 = myList.rbegin(), // through 1st list, and
it2 = addend2.myList.rbegin(); // through 2nd list

while (it1 != myList.rend() || it2 != addend2.myList.rend())
{
if (it1 != myList.rend())
{
first = *it1;
it1++ ;
}
else
first = 0;
if (it2 != addend2.myList.rend())
{
second = *it2;
it2++ ;
}
else
second = 0;

short int temp = first * second;
result = temp % 1000;
carry = temp / 1000;
product.myList.push_front(result);
}

if (carry > 0)
product.myList.push_front(carry);

return product;
}

Main.cpp(测试用例):

int main()
{
char response;
do
{
cout << "\nMultiplication part:" << endl;
cout << "The multiplication of\n\t"
<< number1 << " * " << number2
<< "\nis\n\t" << number1 * number2 << endl;

cout << "\nAdd more integers (Y or N)? ";
cin >> response;
}

当我运行代码时,乘法是错误的。

下面是一个示例运行:123 * 423 的乘积是-507 这显然是不正确的。

我很确定我弄错了乘法的定义,但谁能告诉我哪里搞砸了?

编辑:只是让大家知道,我的代码确实可以编译,但产品有时会出错。我还将我所有的 short int 更改为 long int。

例如:

978 * 878 = 858,684 这是正确的

但是当我使用更大的数字时,问题就出现了。

例子:

432,454 * 765,534 = 330,722,436 这是不正确的。正确答案是 3.32 * 10^11

最佳答案

不要使用 short int对于您的中间值:1000 * 1000 可能会溢出。使用 int ,理想情况下是某个地方 static_assert(1000 * 1000 <= std::numeric_limits<int>::max()), "oops - int is too small!"); .

123 * 423 = 52029。在具有 16 位短裤的二进制补码机上,unsigned short(52029) = -13507。 -13507 % 1000 = -507。我不确定进位发生了什么。虽然。

关于c++ - Bigint *运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17754879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com