Ruby Noob issue

F

Fred Ige

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
 
S

Satish Talim

[Note: parts of this message were removed to make it a legal post.]

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

Fred Ige

Satish said:
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.
 
R

Robert Klemme

Welcome to Ruby, Fred!

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. :)

Kind regards

robert
 
S

Seebs

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. :)

-s
 
B

Bertram Scharpf

Hi,

Am Freitag, 25. Sep 2009, 10:17:53 +0900 schrieb Fred Ige:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top