C++ while
最后修改于 2023 年 1 月 9 日
C++ while 教程展示了如何使用 while 语句在 C++ 中创建循环。
while 语句
while 语句用于创建 while 循环。while 循环是一种控制流语句,它根据给定的布尔条件重复执行代码。
这是 while 循环的一般形式
while (expression) {
statement(s);
}
while 关键字执行大括号括起来的块内的语句。只要表达式的计算结果为 true,就会执行这些语句。
C++ while 示例
以下示例使用 while 语句来计算总和。
simple.cpp
#include <iostream>
int main() {
int i = 0;
int sum = 0;
while (i <= 10) {
sum += i;
i++;
}
std::cout << sum << std::endl;
return 0;
}
我们计算 1..10 的数字的总和。
while 循环有三个部分:初始化、测试和更新。每次执行语句称为一个周期。
int i = 0;
我们初始化 i 变量。它用作计数器。
while (i <= 10) {
...
}
while 关键字后面的括号中的表达式是第二阶段:测试。只要表达式的计算结果为 false,就会执行主体中的语句。
i++;
这是 while 循环的最后第三个阶段:更新。我们递增计数器。请注意,不正确处理 while 循环可能导致无限循环。
$ ./simple 55
C++ while - 计算阶乘
正整数 n 的阶乘,表示为 n!,是所有小于或等于 n 的正整数的乘积。
n! = n * (n-1) * (n-2) * ... * 1
这是计算阶乘的公式。
factorial.c
#include <iostream>
int main() {
int i = 10;
int factorial = 1;
while (i > 1) {
factorial *= i;
i--;
}
std::cout << factorial << std::endl;
return 0;
}
在此示例中,我们使用 while 循环计算 10! 阶乘。
$ ./factorial 3628800
C++ while - 无限循环
while (1) 创建一个无限循环。为了终止循环,我们使用 break 语句。
random.cpp
#include <random>
#include <iostream>
using u32 = uint_least32_t;
using engine = std::mt19937;
int main() {
std::random_device os_seed;
const u32 seed = os_seed();
engine generator(seed);
std::uniform_int_distribution<u32> distribute(1, 30);
while (1) {
int r = distribute(generator);
std::cout << r << " ";
if (r == 22) {
break;
}
}
std::cout << std::endl;
return 0;
}
该示例计算 0..29 之间的随机值。如果它等于 22,则使用 break 语句结束循环。
$ ./random 25 28 9 9 18 6 20 2 5 15 7 11 22
C++ while - 遍历数组
while 语句可用于遍历数组。
loop_array.cpp
#include <iostream>
int main() {
int vals[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int i, sum = 0;
size_t len = sizeof vals / sizeof vals[0];
while (i <= len) {
sum += vals[i];
i++;
}
std::cout << "The sum is: " << sum << std::endl;
return 0;
}
在此示例中,我们有一个整数数组。我们使用 while 语句遍历数组并计算值的总和。
$ ./loop_array The sum is: 55
C++ do while 示例
do while 语句是 while 语句的一种特殊形式,其中块在条件之前执行。因此,块至少执行一次。
do_while.cpp
#include <iostream>
int main() {
int val, sum = 0;
do {
std::cout << "Enter a number: ";
std::cin >> val;
sum += val;
} while(val != 0);
std::cout << "The sum is: " << sum << std::endl;
return 0;
}
该示例要求用户重复输入一个数字。它计算所有这些值的总和。当用户输入零时,循环终止。
$ ./do_while Enter a number: 3 Enter a number: 2 Enter a number: 1 Enter a number: 0 The sum is: 6
本教程专门介绍 C++ 中的 while 语句。