我一直在使用三元运算符编写此代码,以显示
"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::
答案 0 :(得分:2)
您在这里有 {strong> if-statement和conditional 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::" );
// ^^ ^^
请注意额外的括号,这是由于算术左移<<
的{{3}}比条件运算符a?b:c
高。
答案 1 :(得分:1)
您正在混淆实践。实习生(?
)希望值可以评估-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.