溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C語言中怎么使用do-while語句

發(fā)布時間:2022-04-02 10:59:04 來源:億速云 閱讀:223 作者:iii 欄目:編程語言

這篇文章主要介紹“C語言中怎么使用do-while語句”,在日常操作中,相信很多人在C語言中怎么使用do-while語句問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C語言中怎么使用do-while語句”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

while循環(huán)和for循環(huán)都是入口條件循環(huán),即在循環(huán)的每次迭代之前檢查測試條件,所以有可能根本不執(zhí)行循環(huán)體中的內(nèi)容。C語言還有出口條件循環(huán)(exit-condition  loop),即在循環(huán)的每次迭代之后檢查測試條件,這保證了至少執(zhí)行循環(huán)體中的內(nèi)容一次。這種循環(huán)被稱為do while循環(huán)。

看下面的例子:

#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; }

運行結(jié)果:

  • 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循環(huán)也能寫出等價的程序,但是長一些,如程序清單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,\n");         printf("please enter the secret code number: ");         scanf("%d", &code_entered);     }     printf("Congratulations! You are cured!\n");      return 0; }

下面是do while循環(huán)的通用形式:

do     statement while ( expression );

statement可以是一條簡單語句或復合語句。注意,do-while循環(huán)以分號結(jié)尾。

Structure of a =do while= loop=do-while循環(huán)在執(zhí)行完循環(huán)體后才執(zhí)行測試條件,所以至少執(zhí)行循環(huán)體一次;而for循環(huán)或while循環(huán)都是在執(zhí)行循環(huán)體之前先執(zhí)行測試條件。do  while循環(huán)適用于那些至少要迭代一次的循環(huán)。例如,下面是一個包含do while循環(huán)的密碼程序偽代碼:

do {     prompt for password     read user input } while (input not equal to password);

避免使用這種形式的do-while結(jié)構(gòu):

do {    ask user if he or she wants to continue    some clever stuff } while (answer is yes);

這樣的結(jié)構(gòu)導致用戶在回答“no”之后,仍然執(zhí)行“其他行為”部分,因為測試條件執(zhí)行晚了。

到此,關(guān)于“C語言中怎么使用do-while語句”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI