while語(yǔ)句
while語(yǔ)句的一般形式為: while(表達(dá)式)語(yǔ)句; 其中表達(dá)式是循環(huán)條件,語(yǔ)句為循環(huán)體。
while語(yǔ)句的語(yǔ)義是:計(jì)算表達(dá)式的值,當(dāng)值為真(非0)時(shí), 執(zhí)行循環(huán)體語(yǔ)句。其執(zhí)行過(guò)程可用圖 3—4表示。 統(tǒng)計(jì)
從鍵盤(pán)輸入一行字符的個(gè)數(shù)。
#include
void main(){
int n=0;
printf("input a string:\n");
while(getchar()!='\n') n++;
printf("%d",n);
} int n=0;
printf("input a string:\n");
while(getchar()!='\n')
n++;
printf("%d",n);
本例程序中的循環(huán)條件為 getchar()!='\n',其意義是,只要從鍵盤(pán)輸入的字符不是回車就繼續(xù)循環(huán)。循環(huán)體n++完成
對(duì)輸入字符個(gè)數(shù)計(jì)數(shù)。從而程序?qū)崿F(xiàn)了對(duì)輸入一行字符的字符個(gè)數(shù)計(jì)數(shù)。
使用 while語(yǔ)句應(yīng)注意以下幾點(diǎn):
1.while語(yǔ)句中的表達(dá)式一般是關(guān)系表達(dá)或邏輯表達(dá)式,只要表達(dá)式的值為真(非0)即可繼續(xù)循環(huán)。
void main(){
int a=0,n;
printf("\n input n: ");
scanf("%d",&n);
while (n--)
printf("%d ",a++*2);
} int a=0,n;
printf("\n input n: ");
scanf("%d",&n);
while (n--)
printf("%d ",a++*2);
本例程序?qū)?zhí)行 n次循環(huán),每執(zhí)行一次,n值減1。循環(huán)體輸出表達(dá)式 a++*2的值。該表達(dá)式等效于(a*2;a++)
2.循環(huán)體如包括有一個(gè)以上的語(yǔ)句,則必須用{}括起來(lái), 組成復(fù)合語(yǔ)句。
3.應(yīng)注意循環(huán)條件的選擇以避免死循環(huán)。
void main(){
int a,n=0;
while(a=5)
printf("%d ",n++);
} int a,n=0;
while(a=5)
printf("%d ",n++);
本例中while語(yǔ)句的循環(huán)條件為賦值表達(dá)式a=5,因此該表達(dá)式的值永遠(yuǎn)為真,而循環(huán)體中又沒(méi)有其它中止循環(huán)的手
段, 因此該循環(huán)將無(wú)休止地進(jìn)行下去,形成死循環(huán)。4.允許 while語(yǔ)句的循環(huán)體又是 while語(yǔ)句,從而形成雙重循環(huán)。
2015職稱計(jì)算機(jī)考試書(shū)PowerPoint2007中 .. 定價(jià):¥45 優(yōu)惠價(jià):¥42 更多書(shū)籍 | |
2015年全國(guó)職稱計(jì)算機(jī)考試教材(2007模 .. 定價(jià):¥225 優(yōu)惠價(jià):¥213 更多書(shū)籍 |