do while語(yǔ)句是一個(gè)循環(huán)構(gòu)造,其工作方式與while循環(huán)類似,只是該語(yǔ)句總是至少執(zhí)行一次。執(zhí)行語(yǔ)句后,do while循環(huán)檢查條件。如果條件的計(jì)算結(jié)果為true,則執(zhí)行路徑跳回do-while循環(huán)的頂部并再次執(zhí)行。
實(shí)際上,do while循環(huán)并不常用。將條件放在循環(huán)的底部會(huì)模糊循環(huán)條件,這可能會(huì)導(dǎo)致錯(cuò)誤。因此,許多開(kāi)發(fā)人員建議避免do-while循環(huán)。
do while的使用頻率雖然比while循環(huán)和for循環(huán)要低,但也有其適用場(chǎng)景,可以讓代碼更簡(jiǎn)潔。
1 變量作用域
do…while在條件表達(dá)式中的作用域需要在do while的大括號(hào){}外(C語(yǔ)言使用{}定義語(yǔ)句塊),也就是說(shuō),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)用場(chǎ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(),此行代碼要寫(xiě)兩次 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,則此行代碼要寫(xiě)在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(“打開(kāi)文件時(shí)發(fā)生錯(cuò)誤”); return(-1); } do { c = fgetc(fp); // 也是一種交互的方式,上面實(shí)例也是鍵盤輸入,這里是從磁盤獲取數(shù)據(jù) if( feof(fp) ) break ; printf(“%c”, c); }while(1); fclose(fp); return(0);}
do while控制結(jié)構(gòu)常用于輸入一個(gè)字符做判斷的情形:
char c;do{ // do while控制結(jié)構(gòu)常用于輸入一個(gè)字符做判斷的情形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’));
按條件輸入時(shí),do while用起來(lái)更自然:
do{ printf(“Enter n(1–15):”);//要求階數(shù)為1~15 之間的奇數(shù) scanf(“%d”,&n);}while( ! ( (n>=1) && ( n <= 15 ) && ( n % 2 != 0 ) ) );
做菜單設(shè)計(jì)與用戶交互時(shí),通常也使用do while。
-End-