Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C While 循环示例


现实世界中的例子

为了演示 **while 循环** 的实际示例,我们创建了一个简单的“倒计时”程序

示例

int countdown = 3;

while (countdown > 0) {
  printf("%d\n", countdown);
  countdown--;
}

printf("新年快乐!!\n");
自己试试 »

在这个示例中,我们创建一个程序,它只打印 0 到 10(包括 10)之间的偶数

示例

int i = 0;

while (i <= 10) {
  printf("%d\n", i);
  i += 2;
}
自己试试 »

在这个示例中,我们使用 while 循环来反转一些数字

示例

// 具有特定数字的变量
int numbers = 12345;

// 用于存储反转数字的变量
int revNumbers = 0;

// 反转并重新排列数字
while (numbers) {
  // 获取 'numbers' 的最后一个数字并将其添加到 'revNumber'
  revNumbers = revNumbers * 10 + numbers % 10;
  // 删除 'numbers' 的最后一个数字
  numbers /= 10;
}
自己试试 »

为了演示 **while 循环** 与 **if else 语句** 结合的实际示例,假设我们玩一个掷骰子的游戏

示例

如果骰子数字是 6,则打印“Yatzy!”

int dice = 1;

while (dice <= 6) {
  if (dice < 6) {
    printf("没有 Yatzy\n");
  } else {
    printf("Yatzy!\n");
  }
  dice = dice + 1;
}
自己试试 »

如果循环通过从 1 到 5 的值,它将打印“没有 Yatzy”。每当它通过值 6 时,它都会打印“Yatzy!”。



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.