奇怪的错误 - 打印出数组的内容会改变结果,即使我从未改变过结果

时间:2014-12-13 17:36:16

标签: c++ arrays

我正在编写一个函数,用用户输入填充三个数组并计算其值的平均值。但我得到了一个奇怪的错误。

这太奇怪了。当我注释掉这段代码时:

for (int i = 0; i < 5; i++)
    cout << Steve[i] << ",";
cout << endl;

#include <iostream>

using namespace std;
void fill_up(int a[], int size);

void fill_up(int a[], int size)
{
    cout << "Enter " << size << " numbers:\n";
    for ( int i = 0; i < size; i++ )
        cin >> a[i];
    size--;
    cout << "The last array index used is " << size << endl;
}
int main()
{
    int Steve[5];
    int George[5];
    int Mary[5];
    cout << "~ Fill up the Steve array ~" << endl;
    fill_up(Steve, 5);
    cout << "~ Fill up the George array ~" << endl;
    fill_up(George, 5);
    cout << "~ Fill up the Mary array ~" << endl;
    fill_up(Mary, 5);

    /*
    for (int i = 0; i < 5; i++)
        cout << Steve[i] << ",";
    cout << endl;
    */

    int SteveSum, GeorgeSum, MarySum = 0;
    double SteveAvg, GeorgeAvg, MaryAvg;
    for(int i = 0; i < 5; i++)
    {
        SteveSum += Steve[i];
        GeorgeSum += George[i];
        MarySum += Mary[i];
    }
    SteveAvg = ((double) SteveSum ) / 5;
    GeorgeAvg = ((double) GeorgeSum ) / 5;
    MaryAvg = ((double) MarySum ) / 5;

    cout << "Steve's average is " << SteveAvg << endl;
    cout << "George's average is " << GeorgeAvg << endl;
    cout << "Mary's average is " << MaryAvg << endl;
}

以下是在命令行上运行的代码的两个屏幕截图。 ss1 ss2

正如你所看到的那样,当我评论出这个打印数组片段时,史蒂夫的平均值出现了一个奇怪的大数字,但是当我取消注释该片段时它运行正常。这是怎么回事?

1 个答案:

答案 0 :(得分:8)

错:

int SteveSum, GeorgeSum, MarySum = 0;

右:

int SteveSum = 0, GeorgeSum = 0, MarySum = 0;