當前位置

首頁 > 商務英語 > 計算機英語 > c中while的用法

c中while的用法

推薦人: 來源: 閱讀: 2.14W 次

c中while的用法的用法你知道嗎?下面小編就跟你們詳細介紹下c中while的用法的用法,希望對你們有用。

padding-bottom: 66.56%;">c中while的用法

  c中while的用法的用法如下:

while語句的一般形式爲:

while(表達式) 語句

其中表達式是循環條件,語句爲循環體。

while語句的語義是:計算表達式的值,當值爲真(非0)時, 執行循環體語句。其執行過程可用下圖表示。

【例6-2】用while語句計算從1加到100的值。用傳統流程圖和N-S結構流程圖表示算法,見圖:

01.#include <stdio.h>

main(void){

03. int i,sum=0;

04. i=1;

05. while(i<=100){

06. sum=sum+i;

07. i++;

08. }

09. printf("%dn",sum);

10. return 0;

11.}

【例6-3】統計從鍵盤輸入一行字符的個數。

01.#include <stdio.h>

main(void){

03. int n=0;

04. printf("input a string:n");

05. while(getchar()!='n') n++;

06. printf("%d",n);

07. return 0;

08.}

本例程序中的循環條件爲getchar()!='n',其意義是,,只要從鍵盤輸入的字符不是回車就繼續循環。循環體n++完成對輸入字符個數計數。從而程序實現了對輸入一行字符的字符個數計數。

使用while語句應注意以下兩點。

1) while語句中的表達式一般是關係表達或邏輯表達式,只要表達式的值爲真(非0)即可繼續循環。

01.#include <stdio.h>

main(void){

03. int a=0,n;

04. printf("n input n: ");

05. scanf("%d",&n);

06. while (n--) printf("%d ",a++*2);

07. return 0;

08.}