C++ 三元运算符

在 C++ 中,三元运算符是一种简洁的、内联的方式,用于根据条件执行两个表达式中的一个。它也被称为条件运算符。


C++ 中的三元运算符

三元运算符会评估测试条件,并根据条件的结果在两个表达式中执行一个。

语法

condition ? expression1 : expression2;

在这里,会评估 condition,并且

  • 如果 conditiontrue,则执行 expression1
  • 如果 conditionfalse,则执行 expression2

三元运算符需要 **3 个操作数**(conditionexpression1expression2)。因此,它被称为**三元运算符**。


示例: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

注意:只有当结果语句很短时,我们才应该使用三元运算符。

三元运算符与 if…else 对比

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)

注意:不建议使用嵌套三元运算符。因为这会使我们的代码更加复杂。

在我们结束之前,让我们来测试一下您对 C++ 三元运算符的掌握程度!您能解决以下挑战吗?

挑战

编写一个函数,使用三元运算符返回两个数中较大的一个。

  • 返回整数 num1num2 中较大的一个。
  • 三元运算符是编写 if...else 语句的简写方式。它的语法是
  • condition ? trueValue : falseValue
  • 例如,如果 num1 = 4 num2 = 7,则输出应为 **7**。
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战