在C++中显示最高和最低数字

Displaying Hjighest and Lowest number in C++

本文关键字:数字 显示 C++      更新时间:2023-10-16

我正在尝试这种方式。似乎更加简化了。现在只是想知道如何包括月份名称,并让程序输出降雨量最大的月份的名称,而不是用户输入的数字。

#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
    int a[12];
    int x;
    for (x=0; x<12; x++)
    {
        cout << "Insert days of rainfall for month "<<x+1<<endl;
        cin >>a[x];
    }
    int max;
    int min;
    max = a[0];
    min = a[0];
    int e=0;
    while (e<12)
    {
        if (a[e]>max)
        {
             max = a[e];
        }
        else if (a[e]<min)
        {
            min = a[e];
        }
        e++;
        cout<<"The rainiest month was " <<max<<endl;
        cout<<"The least rainy month was " <<min<<endl;
        getch ();
        return 0;
    }

    system("PAUSE");
    return EXIT_SUCCESS;
}

您的average计算有点偏离,在数学方面必须考虑运算顺序。乘法和除法总是先做,然后是加法和减法。你最终得到的结果是,只有dec除以12,然后你把所有其他的日子都加进去。要解决这个问题,你需要把所有月份的加法都用括号括起来,迫使加法先发生,然后再除法。在这种情况下,您可以只使用year变量,因为它已经是所有月份加在一起并除以12。

就您的问题而言,您希望显示输入的最高值和最低值,但我看不到有任何尝试在您的代码中解决此问题。我不太愿意只为你写代码,所以我只简单解释一下你需要做什么。查看每个月的值,每次查看下一个月时,都会将其与您记忆中的当前最高值和当前最低值进行比较。当新的月份有一个新的更高或更低的值时,您将替换您记忆中的值。一旦你每个月都循环,你就会得到最高和最低的价值。

最快、最干净的方法是使用std::vector这样的容器。然后使用std::sort对其进行排序。

// Our container
std::vector<double> userInput;
// Populate the vector. Please don't cin into a double!
// Sort it.
std::sort (userInput.begin(), userInput.end());
// The highest value will be the last value in the vector
// whilst the lowest value will be the first one