【发布时间】:2019-07-08 23:43:20
【问题描述】:
我有一个任务,我需要让用户输入每个月的降雨量。最后,我需要平均降雨量并显示降雨量最高和最低的月份(使用月份名称)。除了显示最低和最高月份外,一切正常。出于某种原因,我的代码总是显示十二月而不是实际的最低和最高月份。最低月 = MONTHS[count];和最高月= MONTHS [countup];是我怀疑导致一些问题的代码行。感谢社区可以提供的任何帮助。
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
const int SIZE = 12;
double RAINFALL[SIZE];
string MONTHS[SIZE] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
for (int counter = 0; counter < SIZE; counter++)
{
cout << "Please enter rainfall for " << MONTHS[counter] << ": ";
cin >> RAINFALL[counter];
while (RAINFALL[counter] < 0.00) // Input validation to prevent neg amounts being entered
{
cout << "Invalid Data (negative rainfall)!" << endl;
cout << "Please re-enter rainfall for " << MONTHS[counter] << ": ";
cin >> RAINFALL[counter];
}
}
int tnum;
double average, sum = 0;
for (tnum = 0; tnum < SIZE; tnum++)
sum += RAINFALL[tnum];
average = sum / SIZE;
cout << "Average rainfall = " << average << endl;
int count;
int lowest;
string lowestMonth = MONTHS[0];
lowest = RAINFALL[0];
for (count = 1; count < SIZE; count++)
{
if (RAINFALL[count] < lowest)
lowest = RAINFALL[count];
lowestMonth = MONTHS[count];
}
cout << "Lowest rainfall in " << lowestMonth << " of: " << lowest << endl;
int countup;
int highest;
string highestMonth = MONTHS[0];
highest = RAINFALL[0];
for (countup = 1; countup < SIZE; countup++)
{
if (RAINFALL[countup] > highest)
highest = RAINFALL[countup];
highestMonth = MONTHS[countup];
}
cout << "Highest rainfall in " << highestMonth << " of: " << highest << endl;
return 0;
}
【问题讨论】:
-
在使用
lowest或highest之前,您永远不会初始化它们,因此行为是未定义的。您还可以在一个循环中组合最低和最高(甚至在输入数据时计算它)
标签: c++