signed or unsigned int problem

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
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.
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.
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?
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
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.