【问题标题】:what is the the purpose of using ? and : in the following code [duplicate]使用的目的是什么?和:在下面的代码中[重复]
【发布时间】:2021-06-25 04:43:32
【问题描述】:

我完全是 C++ 初学者。我最近遇到了一段代码。我似乎不明白?: 的用法。谁能告诉我它是如何工作的?为什么我们使用?:

代码

(j==1 or i==s)?(cout<<"* "):((j==i)?(cout<<" *"):(cout<<" "));

【问题讨论】:

标签: c++


【解决方案1】:

它是一个三元运算符。条件运算符有点类似于 if-else 语句,因为它遵循与 if-else 语句相同的算法,但条件运算符占用的空间更少,有助于以尽可能短的方式编写 if-else 语句。

语法: 条件运算符的形式为。

variable = Expression1 ? Expression2 : Expression3

可以将其可视化为 if-else 语句:

if(Expression1)
{
  variable = Expression2;
}
else
{
  variable = Expression3;
}

【讨论】:

    【解决方案2】:

    三元运算符

    三元运算符评估测试条件并根据条件结果执行代码块。

    它的语法是:

    condition ? expression1 : expression2;
    

    在这里,条件被评估并

    • 如果条件为真,则执行表达式1。

    • 如果条件为假,则执行表达式2。

    你可以在这里找到一个例子 https://www.programiz.com/cpp-programming/ternary-operator

    【讨论】:

      【解决方案3】:

      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";
          
      }
      

      【讨论】:

        猜你喜欢
        • 2020-06-27
        • 2016-05-29
        • 2020-07-30
        • 1970-01-01
        • 2018-05-26
        • 1970-01-01
        • 2018-12-30
        • 1970-01-01
        • 2017-06-03
        相关资源
        最近更新 更多