No compilation errors but program not working

removed
Last edited on
I think you might be misunderstanding how if/else if chains work. If some statement is executed, then none of the others will be. In this case, if the user enters 'C' then it will perform the 3 calculations underneath it and then jump all the way down to the end of the chain at the return 0;.

Does that help?
removed
Last edited on
Here's a small example:
1
2
3
4
5
6
7
8
9
int num1 = 1;
int num2 = 2;
if(num == 1) {
    cout<<"num1 is 1"<<endl;
} else if(num2 == 2) {
    cout<<"num2 is 2"<<endl;
} else {
    cout<<"something else";
}

What do you think this code fragment would output?

EDIT:
I also noticed an important error in your if statement conditions.
if(0 < num1 < 2)
does not do what you think it does. You want this instead:
if(0< num1 && num1 < 2)
Do you know why?
Last edited on
removed

Last edited on
I'm sort of confused reading this thread... I guess I'll drop some info maybe it will explain it a bit.

1
2
3
4
5
6
7
8
9
10
11
12
if(firstCondition) 
{
do this statement;
}
else if (secondCondition)
{
do this statement;
}
else
{
do this statement;
}


A quick walk through of the logic and where Boolean values come in.

If first condition is true, execute the code between the curly braces following the if statement - then skip the rest of the else if's and else connected with this if statement.

If the first condition is false, check to see if the second condition is true. If the second condition is true execute the code between the curly braces following the if else statement - then skip the else statement connected with this block.

If the second condition is false, execute the code connected with this else statement.

When you check your conditions(to determine whether or not to execute code) they return a boolean value based on the truth of those conditions - so int num3 == 3; and you test if(num3==3) the value of the condition will be true.

Your reply to the second question is strange - it doesn't make any sense to check if num1 < 0 and if num1 < 2 , you should just be checking if num1 < 2.
Last edited on
Topic archived. No new replies allowed.