The teacher said that whenever the c
variable is negative then: "the variable a
is negative", but this doesn't make sense.
Is the program written in the wrong form?
In my opinion else should be part of the if(a>0)
with {}
. I don t know why he chose to not use it.
In conclusion, is the correct form like: if(a>0){...}else
and than cout
?
#include <iostream>`
using namespace std;
int main(void) {
int a, b, c;
cin >> a;
cin >> b;
cin >> c;
if (a > 0)
if (b > 0)
if (c > 0)
cout << "they are all positive";
else
cout << "the number a is negative";
}
CodePudding user response:
Your teacher is correct. else
applies to the newest if
, so the value of c
determines the output. (More specifically, the program will only print something when both a
and b
are positive.) You can test this by running the program.
The output "the number a is negative" is illogical, because that's the point of the test. The program is intentionally written incorrectly. If answers to all test questions were obvious, everybody would get the best grade.
CodePudding user response:
You need to use curly brackets
otherwise else
will only apply to the newest if
. The program will only print
when both a
and b
are positive
.
CodePudding user response:
The core problem here is the lack of a clear specification of what the program is supposed to do. I suspect that you do have it, but without it available here I can only explain what the code is doing and how the quote from the teacher can be read as describing what the code does.
To visualise here is a modified version of your code, which is self-explaining (I hope):
#include <iostream>
using namespace std;
int main(void) {
int a, b, c;
cin >> a;
cin >> b;
cin >> c;
if (a > 0)
if (b > 0)
if (c > 0)
cout << "they are all positive"; // true
else
cout << "the number 'c' is negative or zero, 'a' and 'b' are positive";
else
cout << "the number 'b' is negative or zero , 'a' is positive, no idea about 'c'";
else
cout << "the number 'a' is negative or zero , no idea about 'b' and 'c'";
}
I suspect that where this outputs "no idea" is where you might want to use more if
s, in order to describe the other numbers.
Note: I stuck to your style (without {}
). But I recommend to use them generously. In my experience it makes life easier and in my opinion makes code more readable.
I think the quote from the teacher
whenever the c value is negative it say: " the a number is negative" but it doesn't make sense
Should be read as:
'Whenever the c value is negative (and the other two are positive) this code outputs: "the 'a' number is negative", but that doesn't make sense, because a
is in fact positive when this output occurs.
And I agree.