C語(yǔ)言菜鳥(niǎo)基礎(chǔ)教程之條件判斷
(一)if...else
先動(dòng)手編寫(xiě)一個(gè)程序
#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;
}
運(yùn)行結(jié)果:
x is not a positive number!
程序分析:
定義一個(gè)整數(shù)x,并給他賦值。這個(gè)值要么大于0,要么不大于0(等于或小于0)。
若是大于0,則打印x is a positive number!
若不大于0,則打印x is not a positive number!
這里建議不要再使用在線編譯器,而是使用本機(jī)編譯器(蘋(píng)果電腦推薦Xcode,PC推薦dev C++)。在本機(jī)編譯器上設(shè)置斷點(diǎn)逐步執(zhí)行,會(huì)發(fā)現(xiàn)if中的printf語(yǔ)句和else中的printf語(yǔ)句只會(huì)執(zhí)行一個(gè)。這是因?yàn)閕f和else是互斥的關(guān)系,不可能都執(zhí)行。
(二)if...else if...else
稍微改動(dòng)程序
#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;
}
運(yùn)行結(jié)果:
x is zero!
程序分析:
假如條件不止兩種情況,則可用if...else if...else...的句式。
這個(gè)程序里的條件分成三種: 大于0、等于0或小于0。
大于0則打印x is a positive number!
等于0則打印x is zero!
小于0則打印x is a negative number!
注意,x == 0,這里的等號(hào)是兩個(gè),而不是一個(gè)。
C語(yǔ)言中,一個(gè)等號(hào)表示賦值,比如b = 100;
兩個(gè)等號(hào)表示判斷等號(hào)的左右側(cè)是否相等。
(三)多個(gè)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;
}
運(yùn)行結(jié)果:
x belongs to 21~30
程序分析:
(1)
這里把x的值分為好幾個(gè)區(qū)間:(負(fù)無(wú)窮大, 0), [0, 10], [11, 20], [21, 30], [31, 40], (40, 正無(wú)窮大)
(負(fù)無(wú)窮大, 0)用if來(lái)判斷
[0, 10], [11, 20], [21, 30], [31, 40]用else if來(lái)判斷
(40, 正無(wú)窮大)用else來(lái)判斷
(2)
符號(hào)“&&”代表“并且”,表示“&&”左右兩側(cè)的條件都成立時(shí),判斷條件才成立。
相關(guān)文章
C語(yǔ)言中大小端問(wèn)題實(shí)例探索解決方法
這篇文章主要介紹了C語(yǔ)言中大小端問(wèn)題實(shí)例,總的來(lái)說(shuō)這并不是一道難題,那為什么要拿出這道題介紹?拿出這道題真正想要傳達(dá)的是解題的思路,以及不斷優(yōu)化探尋最優(yōu)解的過(guò)程。希望通過(guò)這道題能給你帶來(lái)一種解題優(yōu)化的思路2023-02-02

