我正在编写一个函数,用用户输入填充三个数组并计算其值的平均值.但我得到一个奇怪的错误.
这太奇怪了.当我注释掉这段代码时:
for (int i = 0; i < 5; i++)
cout << Steve[i] << ",";
cout << endl;
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
以下是在命令行上运行的代码的两个屏幕截图.

正如你所看到的那样,当我评论出这个打印数组片段时,史蒂夫的平均值出现了一个奇怪的大数字,但当我取消注释该片段时,它工作正常.这是怎么回事?
错误:
int SteveSum, GeorgeSum, MarySum = 0;
Run Code Online (Sandbox Code Playgroud)
对:
int SteveSum = 0, GeorgeSum = 0, MarySum = 0;
Run Code Online (Sandbox Code Playgroud)