Ruby Noob issue

Hi
I’m really new to Ruby
as such it took me about an hour to register ^^’…
That being said

I am trying to figure out why this program I made keeps returning as “0”

def f(x)
return (5/9) * (x-32)
end
x=1001
print(f(x))

Not complicated at all
I’m just intending for the x value 1001 to plug its self into the
temperature equation and print that value

Thanks for reading

Fred, (5/9) is integer division. The decimal part is truncated leaving
you
with 0. Use (5.0/9) instead.
Satish

Satish T. wrote:

Fred, (5/9) is integer division. The decimal part is truncated leaving
you
with 0. Use (5.0/9) instead.
Satish

Thanks! It works now
I cant believe such a small issue throw me off for so long.

Welcome to Ruby, Fred!

On 09/25/2009 03:17 AM, Fred I. wrote:

Satish T. wrote:

Fred, (5/9) is integer division. The decimal part is truncated leaving
you
with 0. Use (5.0/9) instead.
Satish

Thanks! It works now
I cant believe such a small issue throw me off for so long.

Well, the good news is that you learned it early the hard way and won’t
forget it anytime soon. That will help you avoid such errors in more
complex code where they are more difficult to spot. :slight_smile:

Kind regards

robert

Hi,

Am Freitag, 25. Sep 2009, 10:17:53 +0900 schrieb Fred I.:

Satish T. wrote:

Fred, (5/9) is integer division. The decimal part is truncated leaving
you
with 0. Use (5.0/9) instead.
Satish

Thanks! It works now
I cant believe such a small issue throw me off for so long.

Actually, you’re not the first one to stumble over the
integer/floating point problem.

As expressions are evaluated from left to right, the first number
coerces the value to be Float. You could also say:

(x.to_f - 32) * 5 / 9

Or

class Numeric
def f2c
(to_f - 32) * 5 / 9
end
end

-32.f2c #=> 0.0

Here’s another pitfall about floating point values. Be aware that
aren’t exact in general.

“%20.18f” % 0.3 #=> “0.299999999999999989”

Bertram

On 2009-09-25, Fred I. [email protected] wrote:

Thanks! It works now
I cant believe such a small issue throw me off for so long.

Was it more than two days?

If not, I think you’re ahead of the curve. The real question is how
long
it will take you to figure out why some similar expression is coming out
0 in three or four years. :slight_smile:

-s

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs