我正在尝试获取一系列整数的最小值和最大值,我可以使用此代码获取最小值但不能获取最大值,并且不确定我做错了什么。
#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;
}
最佳答案
问题在于您未初始化的号码。当您第一次进入 while 循环时,程序将采用数字中的任何值(尚未初始化,因此可以是任何值)与 max 和 min 进行比较。然后,您的下一次比较将与您未初始化的值进行比较。
要解决此问题,只需在 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;
}
关于C++ 最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47644847/