tags:

views:

59

answers:

3

I am trying to convert a temperature from Fahrenheit to Celsius:

puts 'Convertir grados Fahrenheit a Celcius'
STDOUT.flush
x = gets.chomp

aprox = (x * 100.0).round(2) / 100.0

resultado = (aprox-32)/1.8

puts resultado

I use the correct formula for converting Fahrenheit to Celcius:

Celsius = Fahrenheit - 32 / 1.8

However, when I run this in the console, it gives me the following error:

`round': wrong number of arguments (1 for 0) (ArgumentError)

I've tried different things but I don't understand why this doesn't work.

+3  A: 

In ruby version prior to 1.9.0 round does not take arguments. It rounds to the nearest integer (see the documentation about floats and the use of round)

Use this instead:

aprox = (x * 100).round() / 100.0

The whole point of multiplying and dividing by 100 is to round the last two digit of x.

Pierre-Luc Simard
You should divide by 100.0 at the end. Otherwise you're performing integer division and just losing the last two digits.
sepp2k
Oh, thank you very much! I want to give you a vote, but I can't, sorry.
Distriker
sepp2k Thanks for pointing that out. I've corrected the code. I've also added a precision based on Greg answer.
Pierre-Luc Simard
+4  A: 

You don't specify what version of Ruby you are using. That makes a difference, because in Rubies prior to 1.9 Float#round did not take a parameter. In 1.9+ it does.

>> RUBY_VERSION #=> "1.9.2"
>> pi = 3.141 #=> 3.141
>> pi.round #=> 3
>> pi.round(1) #=> 3.1
>> 3.141.round(1) #=> 3.1
Greg
Thanks for the information, I don't know this and it's interesting.
Distriker
A: 

activesupport (part of rails) also gives you Float#round(precision)

rogerdpack