无码天堂亚洲内射精品课堂_日韩AV电影在线观看不卡_日韩精品人妻系列无码AV小草_亚洲极限拳头交异物交极端_中文亚洲无线码49vv

學習啦 > 學習英語 > 專業(yè)英語 > 計算機英語 > c語言while的用法

c語言while的用法

時間: 長思709 分享

c語言while的用法

  while語句的一般形式為:while(表達式) 語句其中表達式是循環(huán)條件,語句為循環(huán)體。while語句的語義是:計算表達式的值,當值為真(非0)時, 執(zhí)行循環(huán)體語句。下面小編就為大家介紹下c語言while的用法。
  用while語句計算從1加到100的值。用傳統(tǒng)流程圖和N-S結構流程圖表示算法,見圖:
  #include <stdio.h>
  int main(void){
  int i,sum=0;
  i=1;
  while(i<=100){
  sum=sum+i;
  i++;
  }
  printf("%d\n",sum);
  return 0;
  }
  統(tǒng)計從鍵盤輸入一行字符的個數(shù)。
  #include <stdio.h>
  int main(void){
  int n=0;
  printf("input a string:\n");
  while(getchar()!='\n') n++;
  printf("%d",n);
  return 0;
  }
  本例程序中的循環(huán)條件為getchar()!='\n',其意義是,,只要從鍵盤輸入的字符不是回車就繼續(xù)循環(huán)。循環(huán)體n++完成對輸入字符個數(shù)計數(shù)。從而程序實現(xiàn)了對輸入一行字符的字符個數(shù)計數(shù)。
  使用while語句應注意以下兩點。
  1) while語句中的表達式一般是關系表達或邏輯表達式,只要表達式的值為真(非0)即可繼續(xù)循環(huán)。
  #include <stdio.h>
  int main(void){
  int a=0,n;
  printf("\n input n:    ");
  scanf("%d",&n);
  while (n--) printf("%d  ",a++*2);
  return 0;
  }
  本例程序將執(zhí)行n次循環(huán),每執(zhí)行一次,n值減1。循環(huán)體輸出表達式a++*2的值。該表達式等效于(a*2; a++)。
  2) 循環(huán)體如包括有一個以上的語句,則必須用{}括起來,組成復合語句。
514999