[英]C++ min and max
我正在尝试获取一系列整数的最小值和最大值,并且我能够通过此代码获取最小值,但不能获取最大值,并且不确定我在做什么错。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.