我正在做一个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,这显然是不正确的。
我很确定我搞砸了乘法的定义,但是谁能说出我在哪里搞砸了?
编辑:只是让大家知道,我的代码确实编译,但产品有时是错误的。我也把我所有的短int改为长int。
例如:
978 * 878 =858 684正确
但是当我使用更大的数字时,问题就出现了。
示例:
432,454 * 765,534 = 330,722,436,不正确。正确答案是3.32 * 10^11
发布于 2013-07-19 20:36:09
不要对中间值使用short int:1000 * 1000可能会导致短值溢出。使用int,理想的地方是static_assert(1000 * 1000 <= std::numeric_limits<int>::max()), "oops - int is too small!");。
123 * 423 = 52029。在带有16位短路的两台补码机上,无符号短(52029)= -13507。-13507 % 1000 = -507。我不知道行李怎么了。不过。
https://stackoverflow.com/questions/17754879
复制相似问题