2 + 2 / - 7 * - 7 * 8 - 5 + 7 * -3
Python calculates this expression like this:
2+2/-7*-7*8-5+7*-3 == -8.0
# True
And Ruby like this:
2+2/-7*-7*8-5+7*-3 == 32
# => true
But the correct answer is -8
.
Where am I wrong? Why the Ruby result is different from the Python one?
This example is simpler:
In Ruby (and Python 2.x), 1/2 == 0
. In Python 3.x, it's 0.5
.
What's happening is that in Ruby and Python 2, /
between two integers performs integer division (floors the true result).
The below will give you -8
in Ruby. Note the 2.0
, making that a floating point value:
2+2.0/-7*-7*8-5+7*-3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With