为什么以下代码在阵列中显示上个月的最后一个月,而不是显示降雨量最高和最低降雨量的月份

Why does the following code shows the last month in the array instead of showing the months with the highest and the lowest rainfall?

本文关键字:显示 降雨量 最后一个 代码 阵列 为什么 上个月      更新时间:2023-10-16

我有一个分配,我需要在每个月的降雨量中获取用户输入。最后,我需要平均降雨以及显示最高和最低降雨的月份(使用当月的名称(。除了显示最低和最高月份外,一切都可以使用。由于某种原因,我的代码总是显示12月,而不是实际的最低和最高月份。最低月=月份[count];和最高月份=月份[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-Statement中缺少一个括号,因此仅执行第一行。

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]
];