【问题标题】:How to use nested ternary operators in C++ [duplicate]如何在 C++ 中使用嵌套三元运算符 [重复]
【发布时间】:2018-07-02 23:09:53
【问题描述】:

我正在尝试使用以下代码使用嵌套三元运算符,但它给出了错误的答案,我不明白错误是什么。

#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World\n";
int age, Result ;
cout<<"Enter age:";
cin>>age;

Result=age<0?-1
        :0<=age<=10?0
        :11<=age<=18?1
        :-2;
cout<<"Result is: "<<Result;

return 0;
}

对于输入年龄 13,其给出的结果为 0,对于输入年龄 20,其给出的结果也为 0。我不明白这是什么错误。你可以帮帮我吗?谢谢你。

【问题讨论】:

  • warning C4804: '&lt;=': unsafe use of type 'bool' in operation

标签: c++ ternary-operator


【解决方案1】:

0&lt;=age&lt;=10 没有做你认为的那样。

假设您输入了 11 岁。这个 sn-p 将运行检查 0 &lt;= age,因为年龄是 11,所以这是真的。然后它将检查 true &lt;= 10。 True 被转换成一个整数,所以检查是1 &lt;= 10,这是真的,所以你的三元组将返回 0。

将三元组改为:

Result=                 (age < 0) ? -1
        : ((0<=age) && (age<=10)) ? 0
        :((11<=age) && (age<=18)) ? 1
        :       /*else*/           -2;

【讨论】:

  • 如果您愿意,可以简化为int Result = age &lt; 0 ? -1 : age &lt;= 10 ? 0 : age &lt;= 18 ? 1 : -2;
  • @RetiredNinja +1,公平点。我会编辑它,但问题已关闭,所以我不会费心进一步编辑。
  • 不需要这些括号。
  • 总是很高兴知道这两种方式,因为最短的代码并不总是最易读的,如果你想选择 [1-9]、[11-19] 等,你需要范围的两端。
  • 谢谢@scohe001 和退休忍者
猜你喜欢
  • 2012-02-02
  • 1970-01-01
  • 2013-08-16
  • 2011-10-29
  • 1970-01-01
  • 2011-09-07
相关资源
最近更新 更多