Passing the test task:

Using the ternary operator, replace the initialization of the variable b in the specified code:

 int a = 10; int b; if (a > 0) { if (a < 100) { b = 1; } else { b = 0; } } else { b = -1; } 

In my opinion, here it is necessary to use an embedded ternary operator, I did this:

 int a = 10; int b; b = (a > 0) ? ((a < 100) ? b = 1 : b = 0) : b = -1 ; 

but the test answers that I'm wrong. Where am I wrong and why is this so?

  • one
    What is the actual question? - 0xdb
  • one
    If I understand correctly, you write b = ...? b=1 : b=2 b = ...? b=1 : b=2 , but b=...? 1 : 2 b=...? 1 : 2 - andy.37

1 answer 1

Yes, nested ternary operation. Logically did right. But there was a syntax error - an attempt to assign the value of the variable b inside the ternary operation.

Correctly should be like this:

 int a = 10; int b = a > 0 ? a < 100 ? 1 : 0 : -1; 

Nested expression a < 100 ? 1 : 0 a < 100 ? 1 : 0 returns the value used in the expression above a > 0 ? ВЛОЖЕННОЕ : -1 a > 0 ? ВЛОЖЕННОЕ : -1 , which also returns the value, but directly into the variable b .