while ( 條件 )
{
語句1;
語句2;
....
}
如果條件成立,就會執行循環體中的語句(“循環體”就是while后面大括號{}中的內容)。然后再次判斷條件,重復上述過程,直到條件不成立就結束while循環
while循環的特點:如果while中的條件一開始就不成立,那么循環體中的語句永遠不會被執行.
可以省略大括號{},但是只會影響到while后面的第一條語句。不建議省略大括號。
while ( 條件 )
語句1;
2.代碼
1 #include <stdio.h> 2 3 /* 4 if (條件) 5 { 6 7 } 8 9 while (條件)10 {11 循環體12 }13 14 運行原理15 1.如果一開始條件就不成立,永遠不會執行循環體16 2.如果條件成立,就會執行一次循環體,執行完畢,再次判斷條件是否成立......17 18 break19 直接結束整個while循環20 21 continue22 結束當前的循環體,進入下一次循環體的執行23 24 */25 26 int main()27 {28 // 1.先確定需要重復執行的操作29 30 // 2.再確定約束條件31 32 // 定義一個變量記錄做的次數33 int count = 0;34 35 /*36 while (count<50)37 {38 ++count;39 40 if (count%10 != 0)41 {42 43 }44 }*/45 46 /*47 while (count<50)48 {49 ++count;50 51 if (count%10 == 0)52 {53 // 直接結束這一次循環體,進入下一次循環54 continue;55 }56 57 printf("做第%d次俯臥撐/n", count);58 }*/59 60 while (count < 50)61 {62 ++count;63 64 printf("做第%d次俯臥撐/n", count);65 66 if (count == 20)67 {68 break;69 }70 }71 72 73 return 0;74 }
練習
1 /* 2 提示用戶輸入一個正整數n,計算1+2+3+…+n的和 3 */ 4 5 #include <stdio.h> 6 7 int main() 8 { 9 // 1.提示輸入10 printf("請輸入一個正整數:/n");11 12 // 2.接收輸入13 // 定義變量保存用戶輸入的整數14 int n;15 scanf("%d", &n);16 17 if (n<=0)18 {19 printf("非法輸入/n");20 return 0;21 }22 23 // 3.計算24 // (1 + n) * n / 2;25 // 定義變量保存和26 int sum = 0;27 int number = 0; // 默認被加的數值28 29 while (number < n)30 {31 number++;32 sum += number; // 累加33 }34 35 printf("%d/n", sum);36 37 return 0;38 }
1 /* 2 題目:計算1~100中所有3的倍數的個數 3 */ 4 5 #include <stdio.h> 6 7 int main() 8 { 9 // 記錄3的倍數的個數10 int count = 0;11 12 // 記錄當前檢查的數值13 int number = 0;14 15 while (number < 100)16 {17 number++;18 19 // 說明number是3的倍數20 if (number%3 == 0)21 {22 count++;23 }24 }25 26 printf("1~100內3的倍數的個數:%d/n", count);27 }
3.注意點
1 #include <stdio.h> 2 3 int main() 4 { 5 /* 6 while (10) 7 { 8 printf("哈哈哈哈/n"); 9 }*/10 11 /*12 int a = 10;13 // while (a>0); 死循環14 while (a>0)15 {16 a--;17 printf("哈哈哈/n");18 }*/19 20 // 最簡單的死循環21 //while(1);22 23 return 0;24 }
新聞熱點
疑難解答