簡體   English   中英

C ++最小值和最大值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM