火柴人武林大会
156.74M · 2026-02-04
三目运算符,也叫条件运算符,是 C++ 中唯一一个需要三个操作数的运算符。它是一种紧凑的 if-else 语句的替代形式,用于根据一个条件选择两个值中的一个。 语法格式为:condition ? expression_if_true : expression_if_false
condition: 一个布尔表达式。expression_if_true: 如果 condition 为 true,整个表达式的值就是这个部分的值。expression_if_false: 如果 condition 为 false,整个表达式的值就是这个部分的值。condition 表达式。condition 的结果为 true(或非零),则计算 expression_if_true,并将其结果作为整个三目运算表达式的结果。condition 的结果为 false(或零),则计算 expression_if_false,并将其结果作为整个三目运算表达式的结果。注意: expression_if_true 和 expression_if_false 中只有一个会被执行。下图展示了三目运算的决策流程,像一个铁路岔道。
if-else 的紧凑写法。if-else 是语句,没有返回值。expression_if_true 和 expression_if_false 的类型应该相同或可以隐式转换为一个共同的类型。a ? b : c ? d : e 等价于 a ? b : (c ? d : e)。#include <iostream>
#include <string>
int main() {
int a = 10, b = 20;
// 示例1: 求两数中的最大值
int max_val = (a > b) ? a : b;
std::cout << "Max value is: " << max_val << std::endl; // 输出 20
// 示例2: 判断奇偶性
int num = 7;
std::string result = (num % 2 == 0) ? "Even" : "Odd";
std::cout << num << " is " << result << std::endl; // 输出 7 is Odd
// 示例3: 直接在输出中使用
int score = 85;
std::cout << "Grade: " << (score >= 60 ? "Pass" : "Fail") << std::endl; // 输出 Grade: Pass
return 0;
}
if-else 结构会更清晰。++i),这可能使代码难以理解。例如 int x = a > b ? c++ : d++;printf("%s", score > 60 ? "Pass" : "Fail"); 或变量初始化。if-else 块中更难。int max = a > b ? a : b;const 变量: const int val = (some_condition) ? 100 : 200; 这种情况 if-else 无法做到。return x > 0 ? x : -x; (求绝对值)。constexpr if (C++17) : 对于模板编程,if constexpr 允许在编译时根据条件进行分支,不满足条件的分支代码甚至不会被编译,这比运行时三目运算更强大。lambda 结合: auto my_func = (use_new_version) ? [](int x){...} : [](int x){...};练习1: 求绝对值输入一个整数,使用三目运算符输出其绝对值。
// 答案
#include <iostream>
int main() {
int n;
std::cin >> n;
int abs_n = (n >= 0) ? n : -n;
std::cout << "Absolute value: " << abs_n << std::endl;
return 0;
}
练习2: 两数中的较小者输入两个整数,使用三目运算符输出较小的一个。
// 答案
#include <iostream>
int main() {
int a, b;
std::cin >> a >> b;
int min_val = (a < b) ? a : b;
std::cout << "Min value: " << min_val << std::endl;
return 0;
}
练习3: 性别显示输入一个字符 'M' 或 'F',使用三目运算符输出 "Male" 或 "Female"。
// 答案
#include <iostream>
#include <string>
int main() {
char gender;
std::cin >> gender;
std::string gender_str = (gender == 'M') ? "Male" : "Female";
std::cout << gender_str << std::endl;
return 0;
}
练习4: 打折计算商品价格 price。如果 price 大于等于100,则打9折;否则不打折。使用三目运算符计算并输出最终价格。
// 答案
#include <iostream>
#include <iomanip>
int main() {
double price;
std::cin >> price;
double final_price = (price >= 100) ? price * 0.9 : price;
std::cout << "Final price: " << std::fixed << std::setprecision(2) << final_price << std::endl;
return 0;
}
练习5: 嵌套三目运算输入一个整数,判断它是正数、负数还是零,并输出 "Positive", "Negative" 或 "Zero"。
// 答案
#include <iostream>
#include <string>
int main() {
int n;
std::cin >> n;
std::string result = (n > 0) ? "Positive" : ((n < 0) ? "Negative" : "Zero");
std::cout << result << std::endl;
return 0;
}