C語言菜鳥基礎(chǔ)教程之條件判斷
(一)if...else
先動手編寫一個程序
#include <stdio.h> int main() { int x = -1; if(x > 0) { printf("x is a positive number!\n"); } else { printf("x is not a positive number!\n"); } return 0; }
運行結(jié)果:
x is not a positive number!
程序分析:
定義一個整數(shù)x,并給他賦值。這個值要么大于0,要么不大于0(等于或小于0)。
若是大于0,則打印x is a positive number!
若不大于0,則打印x is not a positive number!
這里建議不要再使用在線編譯器,而是使用本機編譯器(蘋果電腦推薦Xcode,PC推薦dev C++)。在本機編譯器上設(shè)置斷點逐步執(zhí)行,會發(fā)現(xiàn)if中的printf語句和else中的printf語句只會執(zhí)行一個。這是因為if和else是互斥的關(guān)系,不可能都執(zhí)行。
(二)if...else if...else
稍微改動程序
#include <stdio.h> int main() { int x = 0; if(x > 0) { printf("x is a positive number!\n"); } else if(x == 0) { printf("x is zero!\n"); } else { printf("x is a negative number!\n"); } return 0; }
運行結(jié)果:
x is zero!
程序分析:
假如條件不止兩種情況,則可用if...else if...else...的句式。
這個程序里的條件分成三種: 大于0、等于0或小于0。
大于0則打印x is a positive number!
等于0則打印x is zero!
小于0則打印x is a negative number!
注意,x == 0,這里的等號是兩個,而不是一個。
C語言中,一個等號表示賦值,比如b = 100;
兩個等號表示判斷等號的左右側(cè)是否相等。
(三)多個else if的使用
#include <stdio.h> int main() { int x = 25; if(x < 0) { printf("x is less than 0\n"); } if(x >= 0 && x <= 10) { printf("x belongs to 0~10\n"); } else if(x >= 11 && x <= 20) { printf("x belongs to 11~20\n"); } else if(x >= 21 && x <= 30) { printf("x belongs to 21~30\n"); } else if(x >= 31 && x <= 40) { printf("x belongs to 31~40\n"); } else { printf("x is greater than 40\n"); } return 0; }
運行結(jié)果:
x belongs to 21~30
程序分析:
(1)
這里把x的值分為好幾個區(qū)間:(負(fù)無窮大, 0), [0, 10], [11, 20], [21, 30], [31, 40], (40, 正無窮大)
(負(fù)無窮大, 0)用if來判斷
[0, 10], [11, 20], [21, 30], [31, 40]用else if來判斷
(40, 正無窮大)用else來判斷
(2)
符號“&&”代表“并且”,表示“&&”左右兩側(cè)的條件都成立時,判斷條件才成立。