4 Replies - 1091 Views - Last Post: 16 March 2015 - 04:18 AM Rate Topic: -----

#1 Promisek3u  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 23-January 15

Nested Ternary Operators in C

Posted 15 March 2015 - 05:21 PM

Hello, I'm trying to solve this problem here:

http://i.imgur.com/V7IXUGn.png

It tells me the hint of using the ternary operator twice.

I understand that ternary operators are basically:

if (condition is true) ? then (this happens): else (this happens);

But the problem has two consecutive if statements. So far I have this:

y = x != 0 ? a > b ? y = a/x:
                     y = b/x:

             a > b ? y = a/0.000001:
                     y = b/0.000001;



Would that work?

Is This A Good Question/Topic? 0
  • +

Replies To: Nested Ternary Operators in C

#2 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon


Reputation: 6995
  • View blog
  • Posts: 14,628
  • Joined: 16-October 07

Re: Nested Ternary Operators in C

Posted 15 March 2015 - 05:33 PM

View PostPromisek3u, on 15 March 2015 - 08:21 PM, said:

if (condition is true) ? then (this happens): else (this happens);


Not quite. Rather, it's "condition ? return_this_value_if_true : return_this_value_if_false."

So, something like this is valid:
y = (a > B)/> ? a : b;


Was This Post Helpful? 0
  • +
  • -

#3 Promisek3u  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 23-January 15

Re: Nested Ternary Operators in C

Posted 15 March 2015 - 05:57 PM

I'm still having trouble trying to implement the code. What happens when there are two conditions in a row?

Like, the first condition is x != 0, and it is followed by the second condition of a > b.

I don't understand the formatting of that.
Was This Post Helpful? 0
  • +
  • -

#4 Promisek3u  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 23-January 15

Re: Nested Ternary Operators in C

Posted 15 March 2015 - 06:13 PM

Nevermind, thank you for the help and I solved it! :

y = x != 0 ?
    (a > b ? a/x: b/x):
    (a > b ? a/0.000001: b/0.000001);




The return values helped!
Was This Post Helpful? 0
  • +
  • -

#5 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon


Reputation: 6995
  • View blog
  • Posts: 14,628
  • Joined: 16-October 07

Re: Nested Ternary Operators in C

Posted 16 March 2015 - 04:18 AM

Excellent.

Since the divisor is the same, you could also do:
y = x != 0 ?
    (a > b ? a : b ) / x:
    (a > b ? a : b ) / 0.000001);



Note that this still uses three expressions. However, it points your closer to the solution requested, that only uses two.

Good luck.

This post has been edited by baavgai: 16 March 2015 - 04:20 AM
Reason for edit:: bloody b tag thingy

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1