介绍
在本实验中,你将学习 C++ 中的控制流语句。你将学习如何使用 if-else 语句、switch 语句、while 循环、do-while 循环以及 for 循环。
在本实验中,你将学习 C++ 中的控制流语句。你将学习如何使用 if-else 语句、switch 语句、while 循环、do-while 循环以及 for 循环。
有三种基本的流程控制结构:顺序结构、条件结构(或称为决策结构)以及循环结构(或称为迭代结构)。顺序结构:执行过程是从上到下逐行进行。条件结构使用 if-else 语句来验证某个语句是否满足特定条件,然后做出选择。循环结构用于重复执行某些逻辑操作。
程序是由一系列指令组成的。顺序流程是最常见且最直接的流程控制方式,其中程序语句按照编写的顺序依次执行——从上到下按顺序进行。
条件控制有几种类型,包括 if-then、if-then-else、nested-if(if-elseif-elseif-...-else)、switch-case 以及 条件表达式。
#include <iostream>
using namespace std;
int main(){
int mark;
cout<<"Input a number [0-100]: ";
cin>>mark;
// if
if (mark >= 50) {
cout << "Congratulation!" << endl;
cout << "Keep it up!" << endl;
}
cout<<"Input a number [0-100]: ";
cin>>mark;
// if-else
if (mark >= 50) {
cout << "Congratulation!" << endl;
cout << "Keep it up!" << endl;
} else {
cout << "Try Harder!" << endl;
}
cout<<"Input a number [0-100]: ";
cin>>mark;
// nested-if
if (mark >= 80) {
cout << "A" << endl;
} else if (mark >= 70) {
cout << "B" << endl;
} else if (mark >= 60) {
cout << "C" << endl;
} else if (mark >= 50) {
cout << "D" << endl;
} else {
cout << "F" << endl;
}
// switch-case
char oper;
int num1 = 1, num2 = 2, result = 0;
cout<<"Input a char [+ - / *]: ";
cin>> oper;
switch (oper) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
cout << "Unknown operator" << endl;
}
cout<<num1<<oper<<num2<<"="<<result;
return 0;
}
输出:
Input a number [0-100]: 50
Congratulation!
Keep it up!
Input a number [0-100]: 40
Try Harder!
Input a number [0-100]: 85
A
Input a char [+ - / *]: +
1+2=3
条件运算符:条件运算符是一个三元(3 操作数)运算符,形式为 booleanExpr ? trueExpr : falseExpr
。根据 booleanExpr
的值,它会计算并返回 trueExpr 或 falseExpr
的值。
// 返回 "PASS" 或 "FAIL",并输出到 cout
cout << (mark >= 50) ? "PASS" : "FAIL" << endl;
max = (a > b) ? a : b; // RHS 返回 a 或 b
abs = (a > 0) ? a : -a; // RHS 返回 a 或 -a
大括号:如果代码块中只有一条语句,你可以省略大括号 { }
。例如:
if (mark >= 50)
cout << "PASS" << endl; // 只有一条语句,可以省略 { },但不推荐
else { // 多条语句,需要 { }
cout << "FAIL" << endl;
cout << "Try Harder!" << endl;
}
然而,我们建议你保留大括号,即使代码块中只有一条语句,以提高程序的可读性。
同样,循环也有几种类型:for 循环、while-do 循环 和 do-while 循环。
// for-loop
int sum = 0;
for (int number = 1; number <= 100; ++number) {
sum += number;
}
// while-do
int sum = 0, number = 1;
while (number <= 100) {
sum += number;
++number;
}
// do-while
int sum = 0, number = 1;
do {
sum += number;
++number;
} while (number <= 100);
提示用户输入一个上限值。计算从 1 到给定上限值的整数之和,并计算其平均值。
/*
* 计算从 1 到给定上限值的整数之和,并计算其平均值。
*/
#include <iostream>
using namespace std;
int main() {
int sum = 0; // 存储累加的和
int upperbound;
cout << "Enter the upperbound: ";
cin >> upperbound;
// 从 1 到上限值求和
for (int number = 1; number <= upperbound; ++number) {
sum += number;
}
cout << "Sum is " << sum << endl;
cout << "Average is " << (double)sum / upperbound << endl;
// 仅对奇数求和
int count = 0; // 奇数的数量
sum = 0; // 重置 sum
for (int number=1; number <= upperbound; number=number+2) {
++count;
sum += number;
}
cout << "Sum of odd numbers is " << sum << endl;
cout << "Average is " << (double)sum / count << endl;
}
输出:
Enter the upperbound: 15
Sum is 120
Average is 8
Sum of odd numbers is 64
Average is 8
break
语句会中断并退出当前(最内层)的循环。
continue
语句会中止当前迭代,并继续执行当前(最内层)循环的下一次迭代。
break
和 continue
是较差的结构,因为它们难以阅读和理解。只有在绝对必要时才使用它们。你总可以编写出不使用 break
和 continue
的相同程序。
以下程序列出了 2 到上限值之间的非质数。
/*
* 列出 1 到上限值之间的非质数。
*/
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int upperbound;
cout << "Enter the upperbound: ";
cin >> upperbound;
for (int number = 2; number <= upperbound; ++number) {
// 如果在 2 到 sqrt(number) 之间有因子,则不是质数
int maxFactor = (int)sqrt(number);
for (int factor = 2; factor <= maxFactor; ++factor) {
if (number % factor == 0) { // 有因子?
cout << number << " ";
break; // 找到一个因子,无需继续查找
}
}
}
cout << endl;
return 0;
}
输出:
Enter the upperbound: 20
4 6 8 9 10 12 14 15 16 18 20
让我们重写上述程序,列出所有质数。使用一个名为 isPrime
的布尔标志来指示当前的 number
是否是质数,并用于控制打印。
/*
* 列出 1 到上限值之间的质数。
*/
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int upperbound;
cout << "Enter the upperbound: ";
cin >> upperbound;
for (int number = 2; number <= upperbound; ++number) {
// 如果在 2 到 sqrt(number) 之间有因子,则不是质数
int maxFactor = (int)sqrt(number);
bool isPrime = true; // 布尔标志,指示 number 是否是质数
for (int factor = 2; factor <= maxFactor; ++factor) {
if (number % factor == 0) { // 有因子?
isPrime = false; // number 不是质数
break; // 找到一个因子,无需继续查找
}
}
if (isPrime) cout << number << " ";
}
cout << endl;
return 0;
}
输出:
Enter the upperbound: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
研究以下使用 break
和 continue
的程序。
/* 一个神秘的数列 */
#include <iostream>
using namespace std;
int main() {
int number = 1;
while (true) {
++number;
if ((number % 3) == 0) continue;
if (number == 53) break;
if ((number % 2) == 0) {
number += 3;
} else {
number -= 3;
}
cout << number << " ";
}
cout << endl;
return 0;
}
输出:
5 4 2 7 11 10 8 13 17 16 14 19 23 22 20 25 29 28 26 31 35 34 32 37 41 40 38 43 47 46 44 49 53 52
在程序执行到语句结束之前,有几种方式可以终止程序。
exit(): 你可以调用 <cstdlib>
(从 C 的 stdlib.h
移植而来)中的函数 exit(int exitCode)
,来终止程序并将控制权返回给操作系统。按照惯例,返回码为零表示正常终止;而非零的 exitCode
(如 -1)表示异常终止。例如:
abort(): <cstdlib>
头文件还提供了一个名为 abort()
的函数,可用于异常终止程序。
if (errorCount > 10) {
cout << "too many errors" << endl;
exit(-1); // 终止程序
// 或者使用 abort();
}
下图展示了一个嵌套的 for 循环,即在外层 for 循环中包含一个内层 for 循环。
/*
* 打印三角形图案。
*/
#include <iostream>
using namespace std;
int main() {
int size = 8;
for (int row = 1; row <= size; ++row) { // 外层循环打印所有行
for (int col = 1; col <= size-row+1; ++col) { // 内层循环打印每行的所有列
cout << "## ";
}
cout << endl; // 一行结束,将光标移动到下一行
}
return 0;
}
输出:
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ```

以下结构是常用的:
while (true) { ...... }
这看起来像是一个无限循环,但通常通过循环体内的 `break` 或 `return` 语句来终止。这种代码难以阅读——如果可能,应通过重写条件来避免使用。
在本节中,我们介绍了三种控制结构。它们非常有用。你可以将它们组合在一起使用。对于循环要小心,检查终止条件,以避免无限循环。