C語言中do-while語句的2種寫法示例
while迴圈和for迴圈都是入口條件迴圈,即在迴圈的每次迭代之前檢查測試條件,所以有可能根本不執行迴圈體中的內容。C語言還有出口條件迴圈(exit-condition loop),即在迴圈的每次迭代之後檢查測試條件,這保證了至少執行迴圈體中的內容一次。這種迴圈被稱為do while迴圈。
看下面的例子:
#include <stdio.h> int main(void) { const int secret_code = 13; int code_entered; do { printf("To enter the triskaidekaphobia therapy club,\n"); printf("please enter the secret code number: "); scanf("%d",&code_entered); } while (code_entered != secret_code); printf("Congratulations! You are cured!\n"); return 0; }
執行結果:
To enter the triskaidekaphobia therapy club,
please enter the secret code number: 12
To enter the triskaidekaphobia therapy club,
please enter the secret code number: 14
To enter the triskaidekaphobia therapy club,
please enter the secret code number: 13
Congratulations! You are cured!
使用while迴圈也能寫出等價的程式,但是長一些,如程式清單6.16所示。
#include <stdio.h> int main(void) { const int secret_code = 13; int code_entered; printf("To enter the triskaidekaphobia therapy club,\n"); printf("please enter the secret code number: "); scanf("%d",&code_entered); while (code_entered != secret_code) { printf("To enter the triskaidekaphobia therapy club,&code_entered); } printf("Congratulations! You are cured!\n"); return 0; }
下面是do while迴圈的通用形式:
do statement while ( expression );
statement可以是一條簡單語句或複合語句。注意,do-while迴圈以分號結尾。
Structure of a =do while= loop=
do-while迴圈在執行完迴圈體後才執行測試條件,所以至少執行迴圈體一次;而for迴圈或while迴圈都是在執行迴圈體之前先執行測試條件。do while迴圈適用於那些至少要迭代一次的迴圈。例如,下面是一個包含do while迴圈的密碼程式虛擬碼:
do { prompt for password read user input } while (input not equal to password);
避免使用這種形式的do-while結構:
do { ask user if he or she wants to continue some clever stuff } while (answer is yes);
這樣的結構導致使用者在回答“no”之後,仍然執行“其他行為”部分,因為測試條件執行晚了。
總結
到此這篇關於C語言中do-while語句的2種寫法的文章就介紹到這了,更多相關C語言do-while語句寫法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!