問題描述
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))"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!