問題描述
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 不理解類似數(shù)學(xué)的語法,所以
C does not understand math-like syntax, so
if(1<j<=5)
沒有按照您的預(yù)期和想要的方式進(jìn)行解釋;應(yīng)該是
is not interpreted as you expect and want; it should be
if (1 < j && j <= 5)
或類似的.
正如在其他答案中所解釋的,表達(dá)式的計(jì)算方式為
As explained in other answers, the expression is evaluated as
((1 < j) <= 5)
=> ("true" <= 5)
=> "true"
其中true"(布爾值)隱式轉(zhuǎn)換為 1,如 explaneid,例如此處,也參考了標(biāo)準(zhǔn),這解釋了為什么true"必須是less"比" 5(盡管在 C 中談?wù)搹?bool 到 int 的隱式轉(zhuǎn)換"可能并不完全正確)
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")
這篇關(guān)于比較運(yùn)算符的數(shù)學(xué)式鏈接-如“if((5<j<=1))"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!