我正在编写一个程序,该程序处理存储在列表中的大整数,并能够通过重载执行比较和运算符。我在使减法运算符重载时遇到麻烦,程序可以编译,但是运算会导致错误的结果。
操作员部分:
BigInt BigInt::operator-(BigInt addend2) {
BigInt total;
short int first, second, result;
list<short int>::reverse_iterator
it1 = myList.rbegin(),
it2 = addend2.myList.rbegin();
while (it1 != myList.rend() || it2 != addend2.myList.rend()) {
if (it1 != myList.rend()) { first = *it1; }
else { first = 0; }
if (it2 != addend2.myList.rend()) { second = *it2; }
else { second = 0; }
if (first < second) {
first = first + 1000;
short int temp = first - second;
result = temp % 1000;
first = first - 1000;
}
else {
long int temp = first - second;
result = temp % 1000;
}
if (it1 != myList.rend()) {
it1++;
if (first < second) {
first = *it1;
first = first - 1;
*it1 = first;
}
}
if (it2 != addend2.myList.rend()) { it2++; }
total.myList.push_front(result);
}
return total;
}
当我在以下测试文件中运行时:
cout << "\nThe subtraction of\n\t"
<< number1 << " - " << number2
<< "\nis\n\t" << number1 - number2 << endl;
我收到如下输出:
Enter a big integer:
50000
Enter another big integer:
20800
The sum of
50000
+ 20800
is
70800
The bigger number of
50000
and
20800
is
50000
The subtraction of
4-1000
- 20800
is
299999200
Add more integers (Y or N)?
为什么减法运算符会打印出意外的结果?