signed or unsigned int problem

Jan 28, 2014 at 5:19am
I am working on code in class. The idea is that you enter three numbers into the program and it tells you which number is the highest. I have gotten my code to work for all but one case in which the user gives three negative numbers. I tried to make the variables signed integers. But still didn't work right any ideas on how to make this code work for negative numbers? It works otherwise.

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
#include <iostream>

using namespace std;

int ask(string prompt);


int main()
{
    int highest_num = ask("Enter three numbers separated by a space\n");
    cout<<highest_num<<" is the highest.\n";
    return 0;
}


int ask(string prompt)
{
    int a, b, c;
    cout<<prompt;
    cin>>a>>b>>c;
    if(a>b && a>c)
    {
        return a;
    }
    else if(b>a && b>c)
    {
        return b;
    }
    else if(c>a && c>b)
    {
        return c;
    }
}
Last edited on Jan 28, 2014 at 5:30am
Jan 28, 2014 at 6:16am
When I test this code as is, it works fine with any combination of negative/positive numbers.

for example: I input (-1, -5, -17), the output is: -1, which, needless to say, is indeed higher than both -5 and -17.
Jan 28, 2014 at 6:18am
It looks correct.
Maybe you have data entry problems.

(1) Add some debug prints such as:
1
2
3
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl;

after line 20.

And:
cout << "a is biggest" << endl;
etc before each return statement.

(2) The else if (...) statement in line 29 can be replaced with an else as that test should always pass.
Jan 28, 2014 at 6:25am
thanks for looking at this code with me guys! It works for me too! Except when the user enters -52.21 -54.23 -54.1 then it seems to break. I am thinking maybe I should try a making the variable a float type?
Jan 28, 2014 at 6:32am
Yes, if you want the code to work with decimal values, you'll need to use either float or double in place of int.
Last edited on Jan 28, 2014 at 6:32am
Jan 28, 2014 at 7:30am
also you might want to make use of the algorithm max function
http://www.cplusplus.com/reference/algorithm/max/
Topic archived. No new replies allowed.