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??
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 elseif (condition) // You also had a semicolon here, removed it
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" ?