[英]Conditional statement in C with nested if else else if
Found this code in a book: 在书中找到以下代码:
if(a > b)
if(c > b) printf("one");
else if(c == a) printf("two");
else printf("three");
else printf("four");
The question was: The program will never print 问题是: 程序将永远不会打印
a. one b. two c. three d. four
The correct answer is b. two
正确答案是b. two
b. two
Here, I cannot understand why it will not print two
, as in the condition given, c
can equal a
and c
can be greater than b
at the same time 在这里,我不明白为什么它不打印two
,因为在给定的条件下, c
可以等于a
并且c
可以同时大于b
If a
is greater than b
, and c
is not greater than b
, c
can never be equal to a
. 如果a
大于b
且c
不大于b
,则c
永远不能等于a
。
You can distribute the conditions: 您可以分发条件:
one
will print when a > b && c > b
. one
将打印时a > b && c > b
。
two
will print when a > b && c <= b && c == a
. 当a > b && c <= b && c == a
时,将打印two
。 Because of c == a
, these conditions are equivalent to c > b && c <= b
, which can never be true. 由于c == a
,这些条件等效于c > b && c <= b
,这永远不可能成立。
It is because of the else. 这是因为其他。 Specifically, to get to that clause, a > b and c !> b (because if c > b, “one” would print). 具体来说,要获取该子句,请使用a> b和c! Thus, since c !> b, cb, then c != a, so “two” cannot be printed. 因此,由于c!> b,cb,则c!= a,因此无法打印“ 2”。
Another way to look at it, if you rewrite the code logically: 如果您以逻辑方式重写代码,则可以用另一种方式查看它:
a ≤ b
, case "four" 如果a ≤ b
,则为“四个” a > b AND c > b
, case "one" 如果a > b AND c > b
,则为“一个” a > b AND c ≤ b AND c = a
, case "two" 如果a > b AND c ≤ b AND c = a
,则情况为“两个” a > b AND c ≤ b AND c ≠ a
, case "three" 如果a > b AND c ≤ b AND c ≠ a
,则为“三” The only case you can rewrite is the third bullet because with c = a
you have: 唯一可以重写的情况是第三个项目符号,因为使用c = a
您具有:
if a > b AND c ≤ b AND c = a 如果a> b AND c≤b AND c = a
which is logically equivalent to 从逻辑上讲等同于
if a > b AND a ≤ b 如果a> b并且a≤b
Which is never true for any value of a
and b
对于a
和b
任何值都不是真的
you used else in 4 th and 5 th lines. 您在第4行和第5行中使用过else。 you can not use else statment two times. 您不能两次使用else语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.