W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
while循環(huán)重復(fù)指定邏輯表達(dá)式的一組語(yǔ)句。
如果表達(dá)式的計(jì)算結(jié)果為true,則while循環(huán)將繼續(xù)。
while循環(huán)的一般語(yǔ)法如下:
while( expression ) statement1; statement2;
在開(kāi)始時(shí)測(cè)試持續(xù)while循環(huán)的條件。
如果表達(dá)式開(kāi)始為false,則不會(huì)執(zhí)行循環(huán)語(yǔ)句。
如果循環(huán)條件開(kāi)始為真,則循環(huán)體必須將其更改為false以結(jié)束循環(huán)。
以下代碼顯示了如何使用while循環(huán)來(lái)求和整數(shù)
#include <stdio.h>
int main(void)
{
unsigned long sum = 0UL; // The sum
unsigned int i = 1; // Indexes through the integers
unsigned int count = 0; // The count of integers to be summed
printf("\nEnter the number of integers you want to sum: ");
scanf(" %u", &count);
// Sum the integers from 1 to count
while(i <= count)
sum += i++;
printf("Total of the first %u numbers is %lu\n", count, sum);
return 0;
}
上面的代碼生成以下結(jié)果。
以下代碼顯示了如何在語(yǔ)法時(shí)使用。
#include <stdio.h>
int main() {
int num = 0;
while(num<10){
printf("data %d\n",num);
num++;
}
return 0;
}
上面的代碼生成以下結(jié)果。
在這個(gè)例子中,你將在for循環(huán)中嵌套一個(gè)while循環(huán)。
#include <stdio.h>
int main(void)
{
unsigned long sum = 1UL; // Stores the sum of integers
unsigned int j = 1U; // Inner loop control variable
unsigned int count = 5; // Number of sums to be calculated
for(unsigned int i = 1 ; i <= count ; ++i)
{
sum = 1UL; // Initialize sum for the inner loop
j=1; // Initialize integer to be added
printf("\n1");
// Calculate sum of integers from 1 to i
while(j < i)
{
sum += ++j;
printf(" + %u", j); // Output +j - on the same line
}
printf(" = %lu", sum); // Output = sum
}
printf("\n");
return 0;
}
上面的代碼生成以下結(jié)果。
do-while循環(huán)測(cè)試循環(huán)是否應(yīng)該繼續(xù),循環(huán)語(yǔ)句或語(yǔ)句塊總是至少執(zhí)行一次。
do-while循環(huán)的一般表示是:
do { /* Statements for the loop body */ } while(expression);
如果循環(huán)體只是一個(gè)語(yǔ)句,則可以省略大括號(hào)。
在do-while循環(huán)中的括號(hào)后面有一個(gè)分號(hào)。
在do-while循環(huán)中,如果expression的值為true(非零),則循環(huán)繼續(xù)。
只有當(dāng)表達(dá)式的值變?yōu)閒alse(零)時(shí),循環(huán)才會(huì)退出。
以下代碼顯示了如何使用do-while循環(huán)來(lái)反轉(zhuǎn)正數(shù)的數(shù)字:
#include <stdio.h>
int main(void)
{
unsigned int number = 123; // The number to be reversed
unsigned int reversedNumber = 0;
unsigned int temp = 0; // Working storage
temp = number; // Copy to working storage
// Reverse the number stored in temp
do
{
// Add rightmost digit of temp to reversedNumber
reversedNumber = 10*reversedNumber + temp % 10;
temp = temp/10; // and remove it from temp
} while(temp); // Continue as long as temp is not 0
printf("\nThe number %u reversed is %u reversedNumber ehT\n", number, reversedNumber );
return 0;
}
任何非零整數(shù)將轉(zhuǎn)換為true。布爾值false對(duì)應(yīng)于零。
上面的代碼生成以下結(jié)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: