finding the greatest and smallest number

Oct 3, 2012 at 5:30pm
/*Hi, i'm trying to find the maximum and minimum numbers in a list of 5 negative intergers. My program below can always find the minimum, but the maximum always comes out to 0. Does anyone know how to fix this?

Example:
input -54 -76 -43 -87 -52
max == 0
min == -87

as you can see, the max should be -43 but it always comes out to zero... :(*/

int counter;
double num, max, min;
min = 0;
max = 0;
counter = 0;
while(counter < 5)
{
cin >> num;
if(num > max)
max = num;
if(num < min)
min = num;
counter ++;
}
cout << "Your max number is: " << max << endl
<< "Your min number is: " << min << endl;

system("pause");
return 0;
Oct 3, 2012 at 5:41pm
Simply because you assign 0 as the default max value, which is greater than any negative number. Set the max to -100 and it will work
Oct 3, 2012 at 5:47pm
There are (at least) two ways to approach this.

One is to set the max and min values to the first of the actual values.

The other is to set the initial value of max to the smallest possible value which is defined as INT_MIN in the file limits.h (For c++ that's #include <climits> ).

Similarly, initialise min to the largest possible value of INT_MAX.

http://www.cplusplus.com/reference/clibrary/climits/
Oct 3, 2012 at 5:54pm
What a simple error! Tanks so much.
Oct 3, 2012 at 7:20pm
Oh, nice...I like the INT_MIN and INT_MAX method. Thanks
Topic archived. No new replies allowed.