-2

i am using ruby irb

   -1/4
=> -1
   0-1
=> -1
   0-1/4
=> 0

How come it'll be zero for 0-1/4 ?

My calculation is as shown in below picenter image description here

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
  • As I noted in my solution, your calculation is wrong. Basic order of operations - division before subtraction. – kviiri Oct 30 '13 at 12:04
  • See http://stackoverflow.com/questions/5508110/why-is-this-program-erroneously-rejected-by-three-c-compilers/5509621 for a similar question. :-) – the Tin Man Oct 30 '13 at 14:24

2 Answers2

2

1/4 is zero - since both operands are integers, the result is floored to an integer as well. This is the same behavior you're observing earlier with -1/4.

If you want a non-integer result, one or both of the operands have to be floats. For example:

0 - 1 / 4.to_f

to_f makes the interpreter interpret the number as a float.

edit: Your calculation is wrong, by the way. 0 - 1/4 is NOT the same as (0-1) / 4. Always do your operations in the correct order!

kviiri
  • 3,282
  • 1
  • 21
  • 30
1

Because 1 / 4 is 0. And 0 - 0 is 0.

0 - (1 / 4)

You want this:

(0 - 1) / 4

This way you make sure that subtraction happens first. Read up on operator precedence.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367