我是C++的初学者。我最近发现了一段代码。我似乎不理解?
和:
的用法。有人能告诉我它是怎么工作的吗?为什么我们使用?
和:
代码
(j==1 or i==s)?(cout<<"* "):((j==i)?(cout<<" *"):(cout<<" "));
它是一个三元运算符。条件运算符与if-else语句有点相似,因为它遵循与if-erse语句相同的算法,但条件运算符占用的空间较小,有助于以尽可能短的方式编写if-elses语句。
语法:条件运算符的形式为。
variable = Expression1 ? Expression2 : Expression3
它可以被可视化为if-else语句:
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
三元运算符
三元运算符评估测试条件,并根据条件的结果执行代码块。
其语法为:
condition ? expression1 : expression2;
在这里,评估条件并
如果条件为true,则执行表达式1。
并且,如果条件为false,则执行表达式2。
您可以在此处找到示例https://www.programiz.com/cpp-programming/ternary-operator
这是一个短路测试条件if/else,然后放入赋值。
void Main()
{
// ****** Example 1: if/else
string result = "";
int age = 10;
if(age > 18)
{
result = "You can start college";
} else
{
result = "You are not ready for college";
}
// ****** Example 2: if/else with short circuit test condition
result = (age > 18) ? "You can start college" : "You are not ready for college";
}