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 pic
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 pic
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!
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.