I did read the guide on the website and used google in the hopes of finding a solution - no luck.
I'm trying to use an else statement (as the my assignment suggests) but when I do I'm having very strange results. As you can see there are several results that can cout depending on what I put in for temperature and day. The problem I'm having is "Stay home and call work" displays, along with the correct cout, regardless of what I put in.
Example
Please enter the temperature:1
Is it Sunday? (Yes=1, No=2)1
Stay home, but call work.
Work hard and play hard.
Press any key to continue . . .
The correct output should be
Please enter the temperature:1
Is it Sunday? (Yes=1, No=2)1
Work hard and play hard.
Press any key to continue . . .
Why does it want to display "Stay home and call work"? I suspect it has something to do with {}? Any help is much appreciated.
I'm not sure which ifs are nested because of weird indentation, but here's a tip:
When in doubt, encapsulate in-if and in-else code with { } like this:
1 2 3 4 5 6
if (a == b) {
// Code that executes if a == b
}
else {
// Code that executes if a != b
}
Makes it much easier to spot mistakes.
[edit]
Single-line if's don't really need encapsulation, but you should probably do so anyway (especially if you abuse empty lines like this).
The else block executes if the previous if block did not.
Knowing that, let's walk through this logic with temperature=5
1 2 3 4 5 6 7 8 9 10 11 12 13 14
if (temperature<-10 && day == 1) { // temperature is 5, so this is false
cout << "Stay home." <<endl; // this will not print
}
else { // previous if block did not execute (it was false)... so this block WILL execute
cout << "Stay home, but call work." <<endl; // this will print
}
// note that the final else marks the end of that else/if chain. Therefore the following
// if blocks are checked regardless of what the above outcome was
if (temperature <= 0 && temperature >=-10) // this is false
cout << "Dress warm." <<endl; // so this will not print
if (temperature>0) // this is true (temperature is 5, and 5>0
cout <<"Work hard and play hard." <<endl; // so this will print
The end result is that this code prints 2 things, which probably wasn't what you wanted.
You'll want to form one large "else/if" chain:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
if( foo )
{
// executes if foo is true
}
elseif( bar )
{
// executes if foo is false and bar is true
}
elseif( baz )
{
// executes if foo is false, bar is false, and baz is true
}
else
{
// executes if foo, bar, and baz are all false
}