100位数字的总和

时间:2018-11-12 15:50:54

标签: c++ arrays while-loop

我有两个数组,每个数组包含100位数字,我需要从数组末尾的单位位置添加相应的数字,如果有进位则应在下一个索引中添加它应返回另一个包含和。

这是我的代码,似乎有些错误。请帮助我

void sumOf100DigitNumbers(int num1[100], int num2[100], int sum[101]) {
int i, j = 100, k;
for (i = 99; i >= 0; i--)
{
    if (sum[j] == 1)
    {

    }
    else
        sum[j] = 0;

    k = sum[j] + num1[i] + num2[i];
    if (k >= 10)
    {
        sum[j] = k % 10;
        sum[j - 1] = 1;
    }

    else
    {
        sum[j] = k;
    }

    j--;

}


}

测试方法

[TestMethod, Timeout(1000)]
    void Test_sumOf100DigitNumbers2()
    {
        int a[100] = {6, 8, 3, 7, 8, 1, 2, 4, 6, 7, 2, 0, 6, 6, 7, 0, 0, 9, 4, 8, 2, 9, 6, 3, 1, 7, 2, 3, 0, 4, 4, 5, 0, 9, 7, 0, 8, 9, 2, 6, 9, 2, 8, 8, 0, 2, 8, 2, 6, 5, 3, 0, 5, 2, 2, 5, 8, 8, 6, 6, 2, 3, 6, 0, 7, 0, 9, 9, 0, 4, 6, 4, 0, 4, 5, 1, 9, 5, 1, 5, 3, 6, 6, 3, 2, 4, 0, 7, 7, 8, 4, 6, 8, 7, 8, 9, 1, 6, 9, 2};
        int b[100] = { 4, 1, 4, 1, 5, 0, 1, 8, 4, 5, 9, 7, 6, 2, 2, 0, 1, 7, 2, 5, 0, 3, 6, 9, 0, 8, 7, 3, 0, 2, 7, 8, 6, 5, 7, 3, 6, 8, 4, 2, 9, 2, 4, 8, 2, 1, 1, 0, 6, 6, 2, 7, 2, 8, 9, 7, 2, 4, 2, 2, 7, 6, 0, 7, 2, 3, 8, 4, 2, 5, 4, 7, 1, 8, 9, 9, 7, 0, 3, 2, 5, 1, 9, 7, 1, 0, 0, 0, 2, 1, 1, 5, 9, 0, 0, 1, 6, 6, 9, 7 };
        int ans[101] = { 1, 0, 9, 7, 9, 3, 1, 4, 3, 1, 3, 1, 8, 2, 8, 9, 0, 2, 6, 7, 3, 3, 3, 3, 2, 2, 5, 9, 6, 0, 7, 2, 3, 7, 5, 4, 4, 5, 7, 6, 9, 8, 5, 3, 6, 2, 3, 9, 3, 3, 1, 5, 7, 8, 1, 2, 3, 1, 2, 8, 8, 9, 9, 6, 7, 9, 4, 8, 3, 3, 0, 1, 1, 2, 3, 5, 1, 6, 5, 4, 7, 8, 8, 6, 0, 3, 4, 0, 7, 9, 9, 6, 2, 7, 7, 9, 0, 8, 3, 8, 9 };
        int c[101];
        sumOf100DigitNumbers(a, b, c);
        Assert::AreEqual(true, areEqualArrays(ans, c, 101), L"sumOf100DigitNumbers() failed", 1, 2);
    };

但是我的输出如下:

Output

1 个答案:

答案 0 :(得分:2)

您永远不会初始化c。这意味着其内容不确定。您无法预测它将包含哪些值。

因此,当您这样做时:

if (sum[j] == 1)

如果这些不确定的值之一恰好是1,则说明您执行的是您不打算做的进位。

您可以按以下方式对其进行初始化:

int c[101] = { 0 };

然后您可以将其完全删除:

if (sum[j] == 1)
{

}
else
    sum[j] = 0;