do while語句是一個循環(huán)構(gòu)造,其工作方式與while循環(huán)類似,只是該語句總是至少執(zhí)行一次。執(zhí)行語句后,do while循環(huán)檢查條件。如果條件的計算結(jié)果為true,則執(zhí)行路徑跳回do-while循環(huán)的頂部并再次執(zhí)行。
實際上,do while循環(huán)并不常用。將條件放在循環(huán)的底部會模糊循環(huán)條件,這可能會導致錯誤。因此,許多開發(fā)人員建議避免do-while循環(huán)。
do while的使用頻率雖然比while循環(huán)和for循環(huán)要低,但也有其適用場景,可以讓代碼更簡潔。
1 變量作用域
do…while在條件表達式中的作用域需要在do while的大括號{}外(C語言使用{}定義語句塊),也就是說,while()中使用的變量不能在do{}內(nèi)定義,由此,其代碼塊的封裝性比while循環(huán)要弱。
#include int main(){ int x = 0; // while()中使用的x 需在do while前聲明 do { printf( “Hello, world!” ); } while ( x != 0 ); getchar();}
2 應(yīng)用場景
2.1 用戶交互
#include /* printf, scanf, puts, NULL */#include /* srand, rand */#include /* time */int main (){ int iSecret, iGuess; /* initialize random seed: */ srand (time(NULL)); /* generate secret number between 1 and 10: */ iSecret = rand() % 10 + 1; do { printf (“Guess the number (1 to 10): “); scanf (“%d”,&iGuess); // 如果不使用while(),此行代碼要寫兩次 if(iSecretiGuess) puts (“The secret number is higher”); } while(iSecret!=iGuess); puts (“Congratulations!”); return 0;}
以下是類似的用戶交互情形:
#include int main (){ int c; puts (“Enter text. Include a dot (‘.’) in a sentence to exit:”); do { c=getchar(); // 如果不使用do while,則此行代碼要寫在while()內(nèi)或?qū)憙纱? putchar (c); } while(c != ‘.’); return 0;}
2.2 讀取文件
#include int main (){ FILE *fp; int c; int n = 0; fp = fopen(“file.txt”,”r”); if(fp == NULL) { perror(“打開文件時發(fā)生錯誤”); return(-1); } do { c = fgetc(fp); // 也是一種交互的方式,上面實例也是鍵盤輸入,這里是從磁盤獲取數(shù)據(jù) if( feof(fp) ) break ; printf(“%c”, c); }while(1); fclose(fp); return(0);}
do while控制結(jié)構(gòu)常用于輸入一個字符做判斷的情形:
char c;do{ // do while控制結(jié)構(gòu)常用于輸入一個字符做判斷的情形int number;printf(“input number to look for:”);scanf(“%d”,&number);//search(number,num,name);printf(“continue ot not(Y/N)?”);fflush(stdin);scanf(“%c”,&c );}while(!(c==’N’||c==’n’));
按條件輸入時,do while用起來更自然:
do{ printf(“Enter n(1–15):”);//要求階數(shù)為1~15 之間的奇數(shù) scanf(“%d”,&n);}while( ! ( (n>=1) && ( n <= 15 ) && ( n % 2 != 0 ) ) );
做菜單設(shè)計與用戶交互時,通常也使用do while。
-End-