Why does not this work?

Hi guys,
I am trying to learn Ruby. I know some Perl. I cannot make following
script work. Could you please help me understand why “c” value in the
code does not print. It prints “0” for me. Thank you for help.

code:

temp1 = 1
temp2 = 15

puts “F:C”

temp1.upto(temp2) do |i|
c = (i-32)*(5/9)
print i,’:’,c,"\n"
end

On 08/11/11 17:01, Erbay Y. wrote:

puts “F:C”

temp1.upto(temp2) do |i|
c = (i-32)*(5/9)
print i,’:’,c,"\n"
end

Try 5/9 in irb, and then try 5.0/9, and then you may be closer to where
you want to be =]

ruby-1.9.2-p290 :001 > 5.class.name
=> “Fixnum”
ruby-1.9.2-p290 :002 > 5.0.class.name
=> “Float”

Sam

On Mon, Nov 7, 2011 at 8:01 PM, Erbay Y. [email protected]
wrote:

I am trying to learn Ruby. I know some Perl. I cannot make following
script work. Could you please help me understand why “c” value in the
code does not print. It prints “0” for me. Thank you for help.

5/9
=> 0

5.0/9.0
=> 0.555555555555556

5/9 is integer division, so it evaluates to 0. That is multiplied with
i-32 which also evaluates to 0.

The fix is to force floating point division by using at least one
floating point literal in the division operation:

c = (i-32)*(5.0/9)

-Jeremy

Erbay Y. [email protected] wrote:

Hi guys,
I am trying to learn Ruby. I know some Perl. I cannot make following
script work. Could you please help me understand why “c” value in the
code does not print. It prints “0” for me. Thank you for help.

code:

temp1 = 1
temp2 = 15

puts “F:C”

temp1.upto(temp2) do |i|
c = (i-32)*(5/9)
print i,’:’,c,"\n"
end

Thank you for the help guys.

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