【发布时间】:2019-04-03 08:07:33
【问题描述】:
我正在编写一个程序来添加两个大的非负整数(每个大整数最多包含 100 个数字)。然而,在我的程序中,大多数情况下它会给出错误的输出。
我已经完成了main() 函数,但我认为我的代码的问题在于AddTwoBigNumbers() 函数。
#include <stdio.h>
const int MAX_INT_LENGTH = 100;
void AddTwoBigNumbers(char bigN[], char bigM[], char sum[]) {
int i = 0;
int index = 0;
int count = 0;
int index2 = 0;
while (1) {
int sum1 = count;
if (bigM[index]) {
sum1 += bigM[index] - '0';
index++;
}
if (bigN[index2]) {
sum1 += bigN[index2] - '0';
index2++;
}
sum[i] = sum1 % 10 + '0';
i++;
count = sum1 / 10;
if (bigM[index] == 0 && bigN[index2] == 0) {
break;
}
}
if (count) {
sum[i] = count + '0';
i++;
}
sum[i] = 0;
int x, len = 0;
for (x = 0; sum[x]; ++x) {
++len;
}
for (x = 0; x < len / 2; ++x) {
sum[len] = sum[x];
sum[x] = sum[len - x - 1];
sum[len - x - 1] = sum[len];
}
}
int main() {
char bignum[2][MAX_INT_LENGTH]; // bignum[0] and bignum[1] are to store the digits of the two input number
char sum[MAX_INT_LENGTH + 1]; // to store the sum of the two big numbers
// read in two numbers
scanf("%s", bignum[0]);
scanf("%s", bignum[1]);
// calculate sum of the two numbers
AddTwoBigNumbers(bignum[0], bignum[1], sum);
// display the sum on screen
printf("%s\n", sum);
return 0;
}
示例案例如下:
输入:
1
999999999999999999999999999
输出:
1000000000000000000000000000
我的输出:
1000000000000000000000000000
输入:
999999999999999999999999999
999999999999999999999999999
输出:
1999999999999999999999999998
我的输出:
1999999999999999999999999989
【问题讨论】:
-
添加时会发生什么:9 + 9、9 + 99、99 + 9、99 + 99
-
这似乎是learn how to debug your programs的最佳时机。
-
我也建议你以后在做这样的基本测试之前不要写完整的程序。而是编写一小段代码,构建(启用额外警告)并修复可能的错误和警告,然后测试一小段代码。然后你再写一小段代码,构建(和修复问题)和测试。等等。这样一来,解决问题、调试代码以及将错误搜索限制在您添加的最后一小段代码中都会变得更加容易。
-
并且要小心你复制粘贴的代码。如果您需要多次执行相同的操作,而不是复制粘贴代码并进行小的更改(有时会被遗忘或错误),而是将通用代码放入函数中。哪怕只有几行。函数也更容易单独测试和调试。
-
@Kira:你是从左到右添加数字,这是不可能的,即如果你输入
1000和34,你的函数将首先添加1和3.我相信您在反转它之后也不会用\0终止sum变量。因此,首先要反转您的输入,终止求和,然后学习如何使用调试器使用具有明显结果的更简单的输入来单步调试您的代码。