本文目錄一覽:
- 1、C語言中while語句和do while語句具體是如何循環的?
- 2、C語言do-while語句
- 3、c語言do while循環語句舉例
- 4、C語言while do怎麼用?
- 5、關於C語言的do…while語句?
C語言中while語句和do while語句具體是如何循環的?
while()是先判斷括弧裡面的是否成立,成立執行方法體內的語句。
do
while()是先執行方法體內語句再判斷,do
while()至少執行一次。
#includestdio.h
void
main(){
int
sum=0,i;
scanf(“%d”,i);
while(i=10){
sum=sum+i;
i++;
}
printf(“sum=%d\n”,sum);
}
運行輸入1
運行結果:sum=55
再運行一次輸入11
運行結果:sum=0
#includestdio.h
void
main(){
int
sum=0,i;
scanf(“%d”,i);
do{
sum=sum+i;
i++;
}
while(i=10);
printf(“sum=%d\n”,sum);
}
運行輸入1
輸出結果:sum=55
再運行一次輸入11
輸出結果:sum=11
C語言do-while語句
改進版:注意第九行。
#includestdio.h
main()
{
char a;
printf(“Do U Want to Continue(Y/N):”);
do
{
scanf(“%c”,a);
getchar(); //讀取回車符。
if(a==’Y’ || a==’y’)
printf(“This is A\n”); //我加了換行符。
else
if (a==’N’ || a==’n’)
printf(“Thx for UR Attention!\n”);//加了換行符。
else
if(a!=’Y’ a!=’y’ a!=’N’ a!=’n’a!=’#’)//加了「a!=’#’。
printf(“Input Error,Please Input Again!”);
}while(a!=’#’);
}
建議樓主以後要注意細節,因為C語言太靈活了。
c語言do while循環語句舉例
這篇文章主要給大家介紹了關於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,\n”);
printf(“please enter the secret code number: “);
scanf(“%d”, code_entered);
}
printf(“Congratulations! You are cured!\n”);
return 0;
}
C語言while do怎麼用?
C語言中有while循環和do……while循環。
下面舉例說明兩者的用法:
while循環
int i=0;
while(i{
i++;
}
// 執行完後 i=0
do……while循環
int i=0;
do // 第一次不用判斷條件,直接執行循環體
{
i++;
}while(i// 執行完後 i=1
關於C語言的do…while語句?
這個循環語句沒有問題,會輸出0值,因為先執行do語句塊,n–,n的值變成了0,過不了while的判斷。所以輸出了0。就是細節出了問題。首先,這個編譯器不對,這是c++編譯器,其次是頭文件,c++中頭文件要用尖括弧括起來。然後是printf中,應該是”%d”,最後是c++中main函數要有返回值,最後添一句return 0;。
你可以把下面這段代碼複製到這個編譯器中。
#includecstdio
main()
{
int n=1;
do
{
n–;
}
while(n0);
printf(“%d”,n);
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/309143.html