-2

I am trying to use nested ternary operators using following code, but it is giving wrong answer, I am not getting what's the mistake is.

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

For the input age 13 its giving Result as 0 and for input age 20 also its giving result as 0. I am not getting what's the mistake. Could you help me? Thank you.

R June
  • 655
  • 1
  • 6
  • 8

1 Answers1

3

0<=age<=10 is not doing what you think it is.

Let's say you enter an age of 11. This snippet will run the check 0 <= age, which is true since age is 11. Then it will check true <= 10. True gets cast into an integer, so the check is 1 <= 10, which is true, so your ternaries will return 0.

Change the ternaries to:

Result=                 (age < 0) ? -1
        : ((0<=age) && (age<=10)) ? 0
        :((11<=age) && (age<=18)) ? 1
        :       /*else*/           -2;
scohe001
  • 15,110
  • 2
  • 31
  • 51