比较运算符的数学式链接-如“if((5<j<=1))&qu

Math-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))

本文介绍了比较运算符的数学式链接-如“if((5<j<=1))"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int j=42;
if( (5<j<=1) ) {
    printf("yes");
} else {
    printf("no");
}

输出:

yes

为什么输出yes?
条件不是只对了一半吗?

Why does it output yes?
Isn't the condition only half true?

推荐答案

C 不理解类似数学的语法,所以

C does not understand math-like syntax, so

if(1<j<=5)

没有按照您的预期和想要的方式进行解释;应该是

is not interpreted as you expect and want; it should be

if (1 < j && j <= 5)

或类似的.

正如在其他答案中所解释的,表达式的计算方式为

As explained in other answers, the expression is evaluated as

 ((1 < j) <= 5)

 =>  ("true" <= 5)

 =>  "true"

其中true"(布尔值)隐式转换为 1,如 explaneid,例如此处,也参考了标准,这解释了为什么true"必须是less"比" 5(尽管在 C 中谈论从 bool 到 int 的隐式转换"可能并不完全正确)

where "true" (boolean value) is implicitly converted to 1, as explaneid e.g. here, with references to standards too, and this explain why "true" has to be "less than" 5 (though in C might not be totally correct to speak about "implicit conversion from bool to int")

这篇关于比较运算符的数学式链接-如“if((5<j<=1))"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:比较运算符的数学式链接-如“if((5<j<=1))&qu

基础教程推荐