Max between 2 numbers

ok so i just started c++ and my teacher game me a homework. To calculate max between 2 numbers, if a>b than max=a, else max=b. I'm just playing with the expressions and changing little things but anything i did it would show max as b any value a and b had. OR the other result was that max is ~6.03928e-039. What can i do to make it work??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

int main()
{
    float a, b, max;
    cout << "a= ";
    cin >> a;
    cout << "b= ";
    cin >> b;
    if (a > b)
    {
        cout << "max = a ;" << endl;
    }
    else (a < b);
    {
        cout << "max = b ;" << endl;
    }
    cout << "max = " << max<< endl;
    return 0;
}
Hey =)

if a>b than max=a, else max=b.

You never do this. All you do is simply print out "max = a". You never actually set it to that.

1
2
3
4
5
6
7
8
9
10
if (a > b)
    {
        cout << "max = a ;" << endl;
        max = a; // missing this part
    }
    else 
    {
        cout << "max = b ;" << endl;
        max = b; // Missing this part
    }


If you look at the code above, I removed this part - else (a < b);, else does not have any condition, it simply means everything else. If you want it to be specific ,you will need to use else if (condition) // You also had a semicolon here, removed it

http://www.tutorialspoint.com/cplusplus/cpp_if_else_statement.htm
Last edited on
In the above code the following is not part of the else statement:
1
2
3
    {
        cout << "max = b ;" << endl;
    }

It will get executed every time. The only statement that is part of the else is:
(a < b);
Which actually doesn't do anything.

Remember that an else statement has no condition clause (a < b). If the semicolon is removed your compiler would probably warn you about the problem. Your if() statement should look more like:

1
2
3
4
5
6
7
8
    if (a > b)
    {
        cout << "max = a ;" << endl;
    }
    else
    {
        cout << "max = b ;" << endl;
    }


But note that if a and b are equal the above code states that b is the maximum.

Thanks, really appreciate that you answered so fast. Working now, but 1 more question. If i set a as 10 and b as 1 (while running it) shouldn't max have value as 10 and not "a" ?
It does have value as 10. But if you look at your code, you also print out max = a. You can simply remove it if you don't want it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

int main()
{
    float a, b, max;
    cout << "a= ";
    cin >> a;
    cout << "b= ";
    cin >> b;
   if (a > b)
    {
        max = a; 
    }
    else 
    {
        max = b; 
    }
    cout << "max = " << max<< endl;
    return 0;
}
Last edited on
Thanks. Now it's just perfect !
Topic archived. No new replies allowed.