简体   繁体   中英

C++ min and max

I am trying to get the min and max numbers of a series of integers and I am able to get the min with this code but not the max and not sure what i am doing wrong.

#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;
}

The problem lies with your uninitialized number. When you enter your while loop for the first time, the program will take whatever value in number (which has not been initialized thus can be anything) to compare with max and min. Then, your next comparison will be compared to your uninitialized value.

To resolve this, simply take your user input before the while loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM