我有一个作业,我需要获取用户输入的每月降雨量的信息。最后,我需要对降雨量进行平均,并显示降雨量最高和最低的月份(使用月份名称)。除显示最低和最高月份外,所有其他工作正常。由于某种原因,我的代码始终显示12月,而不是实际的最低和最高月份。最下个月= 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;
}
最佳答案
您在if语句中缺少方括号,因此仅执行第一行。
for (count = 1; count < SIZE; count++)
{
if (RAINFALL[count] < lowest) { // <-- BRACKET
lowest = RAINFALL[count];
lowestMonth = MONTHS[count];
} // <-- BRACKET
}
当然,还有更多的模块化方法可以做到这一点:
std::string lowest_month = MONTHS[
std::min_element(&RAINFALL[0], &RAINFALL[SIZE]) - &RAINFALL[0]
];
关于c++ - 为什么以下代码显示数组中的最后一个月,而不显示降雨量最高和最低的月份?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56943737/