C ++ min和max

时间:2017-12-05 01:52:02

标签: c++

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

#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;
}

1 个答案:

答案 0 :(得分:3)

问题出在你未初始化的号码上。当您第一次进入while循环时,程序将采用任何数值(尚未初始化,因此可以是任何值)与max和min进行比较。然后,您的下一个比较将与未初始化的值进行比较。

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

.on()