2017-12-05 24 views
0

一連の整数の最小値と最大値を取得しようとしていますが、このコードで最小値を取得できますが、最大値ではなく、何が間違っているのかわかりません。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; 
} 
+0

どのような結果が得られますか? –

+0

問題は何ですか? –

+0

私の推測は 'while'ループの最初の反復では初期化されていない' number'です。私たちは、OPが得ている結果を一度見るでしょう... – PaSTE

答えて

3

問題は未初期化番号にあります。最初にwhileループを入力すると、プログラムはnumberの値(初期化されていないので何でも構いません)をとり、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; 
}