在 C++ 中,三元运算符是一种简洁的、内联的方式,用于根据条件执行两个表达式中的一个。它也被称为条件运算符。
C++ 中的三元运算符
三元运算符会评估测试条件,并根据条件的结果在两个表达式中执行一个。
语法
condition ? expression1 : expression2;
在这里,会评估 condition
,并且
- 如果
condition
为true
,则执行expression1
。 - 如果
condition
为false
,则执行expression2
。
三元运算符需要 **3 个操作数**(condition
、expression1
和 expression2
)。因此,它被称为**三元运算符**。
示例:C++ 三元运算符
#include <iostream>
#include <string>
using namespace std;
int main() {
double marks;
// take input from users
cout << "Enter your marks: ";
cin >> marks;
// ternary operator checks if
// marks is greater than 40
string result = (marks >= 40) ? "passed" : "failed";
cout << "You " << result << " the exam.";
return 0;
}
输出 1
Enter your marks: 80 You passed the exam.
假设用户输入 **80**。那么,条件 marks >= 40
的计算结果为 true
。因此,第一个表达式 "passed"
被赋给 result。
输出 2
Enter your marks: 39.5 You failed the exam.
现在,假设用户输入 **39.5**。那么,条件 marks >= 40
的计算结果为 false
。因此,第二个表达式 "failed"
被赋给 result。
注意:只有当结果语句很短时,我们才应该使用三元运算符。
1. 三元运算符用于简洁代码
三元运算符最适合用于简单的、内联的条件赋值,并且不会影响可读性。例如,
int age = 20;
string status;
status = (age >= 18) ? "Adult" : "Minor";
在此示例中,将评估条件 age >= 18
。如果为 true,则将 Adult
赋给 status;如果为 false,则将 Minor
赋给 status。
这比使用完整的 if...else
语句要简洁得多,后者看起来会像这样
int age = 20;
string status;
if (age >= 18) {
status = "Adult";
} else {
status = "Minor";
}
在这里,if...else
语句占用了更多行,并且在用于许多简单的条件赋值时可能会使代码混乱。
2. if...else 用于复杂条件的清晰度
if...else
语句更适合复杂的决策过程,以及在可读性和清晰度比简洁性更重要时使用。
假设您需要根据多个条件对天气进行分类。使用带有多个条件语句的三元运算符会很麻烦且难以阅读。在这种情况下,我们使用 if...else
。
让我们看一个例子。
int temperature = 25;
string category;
if (temperature < 10) {
category = "Cold";
} else if (temperature <= 25) {
category = "Moderate";
} else if (temperature > 25) {
category = "Hot";
} else {
category = "Inhabitable";
}
3. 三元运算符隐式返回值
让我们看一个例子来证明这一点。
int number = -4;
string result;
// ternary operator assigns value directly
result = (number > 0) ? "Positive Number" : "Negative Number";
这里,三元运算符根据条件 (number>0)
返回一个值。返回的值存储在 result 变量中。
相比之下,if...else
本身不返回值。因此,对变量的赋值是显式的。
int number = -4;
string result;
// explicit assignment with if...else
if (number > 0)
result = "Positive Number";
else
result = "Negative Number";
嵌套的三元运算符
也可以在一个三元运算符中使用另一个三元运算符。这在 C++ 中称为嵌套三元运算符。
下面是一个使用嵌套三元运算符查找数字是正数、负数还是零的程序。
#include <iostream>
#include <string>
using namespace std;
int main() {
int number = 0;
string result;
// nested ternary operator to find whether
// number is positive, negative, or zero
result = (number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");
cout << "Number is " << result;
return 0;
}
输出
Number is Zero
在上面的示例中,请注意三元运算符的使用,
(number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");
这里,
(number == 0)
是第一个测试条件,用于检查 number 是否为 0。如果是,则将字符串值"Zero"
赋给 result。- 否则,如果第一个条件为
false
,则会评估第二个测试条件(number > 0)
。
注意:不建议使用嵌套三元运算符。因为这会使我们的代码更加复杂。