【问题标题】:I cant seem to get whats wrong with my code, I cant get the output我似乎无法理解我的代码有什么问题,我无法获得输出
【发布时间】:2019-11-21 19:42:52
【问题描述】:

我一直在使用三元运算符编写奇偶数代码,但它正在显示

"expected primary-expression before ‘?’ token"

我的代码:

{  
  int n;
  cout<<"enter any numbner::";
  cin>>n;

  if(n%2==0) ? cout<<"no is even::" : cout<<"no is odd::";

  return 0;
}

预期的 o/p 是:

enter any number:20
no is even::

【问题讨论】:

    标签: c++ c++11 if-statement syntax conditional-operator


    【解决方案1】:

    你有一个混合if-statementconditional operator在这里:

      if (n % 2 == 0) ? cout << "no is even::" : cout << "no is odd::";
    //^^^           ^^^^
    

    这是错误的。您可以使用条件运算符编写,例如

    (n % 2 == 0) ? std::cout << "no is even::" : std::cout << "no is odd::";
    

    或更紧凑

    std::cout << ( n % 2 == 0 ? "no is even::" : "no is odd::" );
    //           ^^                                           ^^
    

    注意额外的括号,这是由于算术左移&lt;&lt;precedence 高于条件运算符a?b:c

    【讨论】:

      【解决方案2】:

      您正在混淆实践。 ternery (?) 期望值来评估 - if 没有给出值。

      要么做:

      if(n%2==0) {
          cout<<"no is even::";
      } else { 
          cout<<"no is odd::";
      }
      

      std::string value = (n%2) ? "odd" : "even";
      cout << value;
      // for bonus points you can do this without a temporary variable.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-18
        • 2021-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-31
        • 1970-01-01
        • 2016-09-18
        相关资源
        最近更新 更多