比较运算符的类似数学的链接 - 例如,“if((< j< = 1))" [英] Math-like chaining of the comparison operator - as in, "if ( (5<j<=1) )"

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

问题描述

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

输出:

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

As explained in other answers, the expression is evaluated as

 ((1 < j) <= 5)

 =>  ("true" <= 5)

 =>  "true"

其中true(布尔值)被隐式转换为1,例如,例如此处,也参考了标准,这解释了为什么真实必须少比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((&lt; j&lt; = 1))&quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆