C++ 条件语句 If … Else
C++ 条件与 If 语句
C++ 支持数学中的一般逻辑条件:
- 小于: a < b
- 小于等于: a <= b
- 大于: a > b
- 大于等于: a >= b
- 等于: a == b
- 不等于: a != b
您可以使用这些条件为不同的条件执行不同的操作。
C++ 有以下条件语句:
- 如果指定的条件为 true,则使用
if指定要执行的代码块 - 如果相同条件为 false,则使用
else指定要执行的代码块 - 如果第一个条件为 false,则使用
else if指定要测试的新条件 - 使用
switch指定要执行的许多可选代码块
if 语句
如果条件为 true,请使用 if 语句指定要执行的 C++ 代码块。
语法
if (condition) {// 如果条件为 true,则要执行的代码块}
请注意,
if 是小写字母。大写字母(If 或 If)将生成错误。在下面的实例中,我们测试两个值,以确定 20 是否大于 18。如果条件为 true,则输出(打印)一些文本:
实例
#include <iostream>using namespace std;int main() {if (20 > 18) {cout << "20 is greater than 18";}return 0;}
我们还可以判断变量:
实例
#include <iostream>using namespace std;int main() {int x = 20;int y = 18;if (x > y) {cout << "x is greater than y";}return 0;}
实例解释
在上面的例子中,我们使用两个变量 x 和 y 来测试 x 是否大于 y(使用 > 操作符)。因为 x 是20,y 是 18,我们知道 20 大于 18,所以我们在屏幕上输出 "x > y"。
else 语句
如果条件为 false,则使用 else 语句指定要执行的代码块。
语法
if (condition) {// 如果条件为 true,则要执行的代码块} else {// 如果条件为 false,则要执行的代码块}
实例
#include <iostream>using namespace std;int main() {int time = 20;if (time < 18) {cout << "Good day.";} else {cout << "Good evening.";}return 0;}
实例解释
在上面的实例中,时间(20)大于 18,因此条件为 false。因此,我们转到 else 条件并在屏幕上输出 "Good evening"。如果时间少于 18,程序将打印 "Good day"。
else if 语句
如果第一个条件为 false,则使用 else if 语句指定新条件。
语法
if (condition1) {// 如果条件为 true,则要执行的代码块} else if (condition2) {// 如果条件 1 为 false,而条件 2 为 false,则要执行的代码块 is true} else {// 如果条件 1 为 false,条件 2 为 false,则要执行的代码块}
实例
#include <iostream>using namespace std;int main() {int time = 22;if (time < 10) {cout << "Good morning.";} else if (time < 20) {cout << "Good day.";} else {cout << "Good evening.";}return 0;}
实例解释
在上面的示例中,时间(22)大于 10,因此第一个条件为 false。else if 语句中的下一个条件也是 false,因此我们转到 else condition,因为 condition1 和 condition2 都是 false,并输出到屏幕上 "Good evening"。
然而,如果时间是 14,我们的程序将打印 "Good day."
简写 If…Else (三元运算符)
还有一个缩写 if-else,它被称为 三值运算符,因为它由三个操作数组成。它可以用来用一行代码替换多行代码。它通常用于替换简单的 if-else 语句
语法
variable = (condition) ? expressionTrue : expressionFalse;
一般写法:
实例
#include <iostream>using namespace std;int main() {int time = 20;if (time < 18) {cout << "Good day.";} else {cout << "Good evening.";}return 0;}
您也可以像这样简写:
实例
#include <iostream>#include <string>using namespace std;int main() {int time = 20;string result = (time < 18) ? "Good day." : "Good evening.";cout << result;return 0;}