gpt4 book ai didi

c++ - 阵列程序奇怪的输出

转载 作者:太空宇宙 更新时间:2023-11-04 15:44:00 25 4
gpt4 key购买 nike

我正在尝试编写一个代码来列出油耗,到目前为止它是有效的。问题是它没有按应有的方式工作。下面的代码要求输入,然后显示所述输入的列表以及计算出的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com