[英]Weird error - printing out contents of an array changes the result, even though I never changed the result
I'm writing a function that fills up three arrays with user input and calculates the average of their values. 我正在编写一个函数,用用户输入填充三个数组并计算其值的平均值。 But I am getting a weird error.
但是我收到一个奇怪的错误。
This is so weird. 太奇怪了 When I comment out this code:
当我注释掉这段代码时:
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;
}
Here are two screenshots of the code running on command line. 这是在命令行上运行的代码的两个屏幕截图。
As you can see when I comment out that print array snippet, Steve's average comes out to a weird large number, but when I uncomment that snippet it works fine. 如您所见,当我注释掉该打印数组代码段时,Steve的平均值出现了很多怪异现象,但是当我取消注释该代码段时,它的效果很好。 What's going on?
这是怎么回事?
Wrong: 错误:
int SteveSum, GeorgeSum, MarySum = 0;
Right: 对:
int SteveSum = 0, GeorgeSum = 0, MarySum = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.