我正在努力理解我教授编写的代码。代码中有一行说
a =(b> c)? c:b;
其中a,b和c只是浮点变量。这是我第一次看到这个表达。我试图谷歌它但没有出现。对此的任何解释或链接都受到欢迎。谢谢。
答案 0 :(得分:5)
这是一个三元表达。三元表达式采用以下形式:
condition ? <result_if_true> : <result_if_false>
三元表达式可以转换为if
语句:
if (condition) {
<result_if_true>;
} else {
<result_if_false>;
}
三元表达式相对于等效if
语句的优点是变量声明。例如,以下if
语句和三元表达式是等价的,但很明显哪个更简洁:
int seconds = 4;
// ===== USING IF STATEMENT =====
string secs_string;
if (seconds == 1) {
secs_string = "second";
} else {
secs_string = "seconds";
}
cout << "You have " << seconds << " "<< secs_string << " remaining." << endl;
// Output: You have 4 seconds remaining.
// ===== USING TERNARY EXPRESSION =====
string secs_string = (seconds == 1) ? "second" : "seconds";
cout << "You have " << seconds << " "<< secs_string << " remaining." << endl;
// Output: You have 4 seconds remaining.
请注意,使用if
需要在if
语句之外对字符串进行单独声明,而使用三元表达式时,可以内联完成。
进一步阅读
答案 1 :(得分:3)
这称为条件运算符,也称为三元运算符。它只是压缩形式的if语句。
a = (b > c) ? c : b;
与
具有相同的效果if (b > c) a = c; else a = b;