C 分钟和最大

C++ min and max

本文关键字:分钟      更新时间:2023-10-16

我正在尝试获取一系列整数的最小数量和最大数字,并且我能够使用此代码获得最小值,但不确定我在做什么错。

#include <iostream>
#include <climits>
using namespace std;

int main()
{
//Declare variables.
int number, max, min;
//Set the values.
max = INT_MIN;
min = INT_MAX;
cout << "Enter -99 to end series" << endl;
while (number != -99)
{
    //Compare values and set the max and min.
    if (number > max)
        max = number;
    if (number < min)
        min = number;
    //Ask the user to enter the integers.
    cout << "Enter a number in a series: " << endl;
    cin >> number;
}
//Display the largest and smallest number.
cout << "The largest number is: " << max << endl;
cout << "The smallest number is: " << min << endl;
system("pause");
return 0;
}

问题在于您的非原始数字。当您第一次输入WARE循环时,该程序将采用任何数字值(尚未初始化的值,因此可以是任何东西),以与Max和Min进行比较。然后,将您的下一个比较与您的非初始化价值进行比较。

要解决此问题,只需将用户输入在while while循环之前。

cout << "Enter -99 to end series" << endl;
//Ask the user to enter the integers.
cout << "Enter a number in a series: " << endl;
cin >> number;
while (number != -99)
{
    //Compare values and set the max and min.
    if (number > max)
        max = number;
    if (number < min)
        min = number;
    //Ask the user to enter the integers.
    cout << "Enter a number in a series: " << endl;
    cin >> number;
}