我正在尝试编写代码以列出汽油里程,到目前为止,它仍然有效。问题在于它无法正常运行。下面的代码要求输入,然后显示所述输入的列表以及计算出的MPG。
#include<iostream>
using namespace std;
//function prototype
void CalcAverage (int arr1[], float arr2[], int size);
//global variables
int mil [3];
float gal [3];
float mpg [3];
//main program
int main()
{
char month [7];
int day [3];
cout << "Please enter the starting month" << endl;
cin >> month;
cout << "Please enter starting day entry 1" << endl;
cin >> day [0];
cout << "entry 2" << endl;
cin >> day [1];
cout << "entry 3" << endl;
cin >> day [2];
cout << "entry 4" << endl;
cin >> day [3];
cout << "Please enter gallons entry 1" << endl;
cin >> gal [0];
cout << "entry 2" << endl;
cin >> gal [1];
cout << "entry 3" << endl;
cin >> gal [2];
cout << "entry 4" << endl;
cin >> gal [3];
cout << "Please enter miles entry 1" << endl;
cin >> mil [0];
cout << "entry 2" << endl;
cin >> mil [1];
cout << "entry 3" << endl;
cin >> mil [2];
cout << "entry 4" << endl;
cin >> mil [3];
CalcAverage (mil,gal,4);
cout << "Week of" << "\t\tGallons" << "\t\tMiles" << "\t\tMPG" << endl;
cout << "_ _ _ _ _ _ _" << "\t_ _ _ _ _" << "\t_ _ _ _" << "_ _ _ _" << endl;
cout << month << " " << day [0] << "\t" << gal [0] << "\t\t" << mil [0] << "\t\t" << mpg [0] << endl;
cout << month << " " << day [1] << "\t" << gal [1] << "\t\t" << mil [1] << "\t\t" << mpg [1] << endl;
cout << month << " " << day [2] << "\t" << gal [2] << "\t\t" << mil [2] << "\t\t" << mpg [2] << endl;
cout << month << " " << day [3] << "\t" << gal [3] << "\t\t" << mil [3] << "\t\t" << mpg [3] << endl;
system("PAUSE");
}
//function definition
void CalcAverage (int arr1[], float arr2[], int size)
{
//statements
mpg [0] = mil [0] / gal [0];
mpg [1] = mil [1] / gal [1];
mpg [2] = mil [2] / gal [2];
mpg [3] = mil [3] / gal [3];
}
代码有效,我没有收到任何错误。但是,当代码显示输出时,某些结果会被切换或混杂,或者完全是随机的(我的第3 gal输入变为我的第1 mil输入,等等)是什么导致了此问题,我该如何解决?
最佳答案
请注意,当声明类似mil[3]
的数组时,该数组具有mil[0]
,mil[1]
和mil[2]
的元素。因此,使用mil[3]
是无效的。将数组声明更改为:
int mil [4];
float gal [4];
float mpg [4];
也是使用
[4]
代替[3]
的日子关于c++ - 数组程序奇怪的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19555940/