C++ 最小值和最大值

标签 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;
}

最佳答案

问题在于您未初始化的号码。当您第一次进入 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/

相关文章:

c++ - 有没有办法检查标准库 c++ 中的队列何时已满?

c++ - 使用 emplace_back 避免移动构造函数调用的最佳方法?

c++ - 结构中的结构,初始化

C++ 外部链接

C++CLI。 native 部分是否用纯 C++ 编写但在 CLI 中编译的速度与纯 native C++ 一样快?

c++ - 在变量中存储多个值

c++ - 如何确定 POINT 是否在按钮区域内

c++ - 在 qt c++ 应用程序中显示实时视频的问题

c++ - 这是使用 alloca 的好理由吗?

c++ - PCL 在没有云复制的情况下对八叉树应用过滤器