条件运算符
本课属于 Coddy C++ 学习旅程的“基础知识”单元。第 30 课,共 74 课。
条件运算符是一种简单的单行 if-else 语句。它的语法如下:
variable = (condition) ? value_if_true : value_if_false;条件运算符会计算条件。如果条件为 true,它会将 value_if_true 赋给变量;否则,会将 value_if_false 赋给变量。
例如:
int age = 20;
std::string message = (age >= 18) ? "Adult" : "Minor";在这个示例中,由于 age 大于或等于 18,message 会被赋值为 "Adult"。如果 age 小于 18,message 就会被赋值为 "Minor"。
你可以根据需要叠加任意多个条件:
vrbl = (cond1) ? val1 : (cond2) ? val2 : val3;例如:
int score = 100;
std::string result = (score == 100) ? "Perfect!" : (score >= 90) ? "Excellent" : "Good";在这个例子中,由于 score == 100 为真,result 将被赋值为 "Perfect!"。如果分数是 95,则会被赋值为 "Excellent"。
挑战
入门创建一个程序,使用条件运算符检查一个数字是正数、负数还是零。程序应执行以下操作:
- 接收用户输入的一个整数。
- 使用条件运算符判断这个数字是正数、负数还是零。
- 按照以下格式打印结果:
"The number is [positive/negative/zero]"。
亲手试试
#include <iostream>
int main() {
int number;
std::cin >> number;
std::string result = "";
// 在下方编写你的代码
std::cout << "The number is " << result << std::endl;
return 0;
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: C++ 在线编译器