C語言while語句的用法
- 互聯網
- 關注:1.83W次
while語句的一般形式為: while(表達式) 語句其中表達式是循環條件,語句為循環體。
#include
intmain(void){
inti,sum=0;
i=1;
while(i<=100){
sum=sum+i;
i++;
}
printf("%dn",sum);
return0;
}
#include
intmain(void){
intn=0;
printf("input a string:n");
while(getchar()!='n')n++;
printf("%d",n);
return0;
}
本例程序中的循環條件為getchar()!='n',其意義是,,只要從鍵盤輸入的字符不是回車就繼續循環。循環體n++完成對輸入字符個數計數。從而程序實現了對輸入一行字符的字符個數計數。使用while語句應注意以下兩點。1) while語句中的表達式一般是關係表達或邏輯表達式,只要表達式的值為真(非0)即可繼續循環。
#include
intmain(void){
inta=0,n;
printf("ninput n: ");
scanf("%d",&n);
while(n--)printf("%d ",a++*2);
return0;
}
本例程序將執行n次循環,每執行一次,n值減1。循環體輸出表達式a++*2的值。該表達式等效於(a*2; a++)。2) 循環體如包括有一個以上的語句,則必須用{}括起來,組成複合語句。
- 文章版權屬於文章作者所有,轉載請註明 https://miaozhigu.com/sm/hulianwang/dexlo9.html