problem to lounge a program

//This program display the minimum and the maximum of 6 numbers
#include <iostream>
using namespace std;

int main()
{
short int number, min=65535,max=0,counter=0;


do
{
cout << "Enter number:";
cin >>number;

counter++;

if (number>max)
{
max=number;
}

else if(min>=number)
{
min=number;
}
}
while (counter!=6);

cout <<"Minimum of the numbers:"<<min<<endl<<"Maximum of the numbers:"<<max<<endl;

system("PAUSE");

return 0;
}




It always display minimum as -1.
Can somebody tell me why???????
@kingdro

Because the value of short int is from -32,768 to 32,767. So, to use the 65535, change to just int.

If you cout the variable, short int min, you'll find its value is -1.
Last edited on
@whitenite1 you are simply differentiating between signed and unsigned
I think the else is causing the problem.
There is no need to set the values of min & max to any magic number initially.

Just initialise them to zero, and the program will be fine.

It is a separate issue altogether if you want to test for overflow on a particular type.

Can you please use code tags in the future? The <> button on the right.
There is no need to set the values of min & max to any magic number initially.

Just initialise them to zero, and the program will be fine.


No, it wouldn't.

If the user never entered a value less or equal to zero min would be reported incorrectly, the same if the user never entered a value greater than or equal to zero for max.

The cause of the problem is your if/else if. There should be no else.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <limits>
using namespace std;

int main()
{
    typedef short int num_type ;
    num_type min = std::numeric_limits<num_type>::max() ;
    num_type max = std::numeric_limits<num_type>::min() ;

    num_type number ;
    unsigned counter = 0 ;
    do
    {
        cout << "Enter number:";
        cin >>number;

        counter++;

        if (number>max)
        {
            max=number;
        }

        // else if(min>=number)
        if ( min > number )
        {
            min=number;
        }
    }
    while (counter!=6);

    cout <<"Minimum of the numbers:"<<min<<endl<<"Maximum of the numbers:"<<max<<endl;

    system("PAUSE");

    return 0;
}

Topic archived. No new replies allowed.