(一)
先動手編寫一個程序:
#include <stdio.h>int main(){ if(1) { printf("The condition is true!/n"); } return 0;}
運行結果:
The condition is true!
再把1依次改為,2,5,100,-10,發現運行結果完全一樣。
再改成if(0),此時發現沒有運行結果,說明printf()語句沒被執行。
C語言把判斷語句中的任何非0或非空的值當作真。所以if(1), if(2), if(5), if(100), if(-10)的效果是一樣的。
(二)
再編寫一個程序:
#include <stdio.h>int main(){ int a = 100; if(a > 0) { printf("The condition value is %d/n", (a > 0)); } return 0;}
運行結果:
The condition value is 1
分析:
a = 100,a > 0成立 ,所以if( a > 0)等價于if(1)。
在C語言中,判斷語句是有值的,要么為1,要么為0。比如本程序中a > 0的值就是1。
(三)
最后編寫一個程序:
#include <stdio.h>int main(){ char c1 = '/0'; if(c1) { printf("The condition is true!/n"); } else { printf("The condition is false!/n"); } char c2 = ' '; if(c2) { printf("The condition is true!/n"); } else { printf("The condition is false!/n"); } char c3 = 'A'; if(c3) { printf("The condition is true!/n"); } else { printf("The condition is false!/n"); } return 0;}
運行結果:
The condition is false!The condition is true!The condition is true!
說明:C語言中用'/0'來表示空字符??崭?#39; ‘也是一個字符,這從if(c2)條件為真就可以看出來。
新聞熱點
疑難解答