I'm trying to give a file as input, have it changed within the program, and save the result to a file that is output. But the output file is the same as the input file. :/ Total n00b question, but what am I doing wrong?:
puts "Reading Celsius temperature value from data file..."
num = File.read("temperature.dat")
celsius = n开发者_如何学编程um.to_i
farenheit = (celsius * 9/5) + 32
puts "Saving result to output file 'faren_temp.out'"
fh = File.new("faren_temp.out", "w")
fh.puts farenheit
fh.close
I have tested the code on my machine and I have correctly the "faren_temp.out" file. Nothing is wrong ?
Temperature.dat
23
faren_temp.out
73
You just have a problem in the result. "celsius" must be a float variable in order to do a float division (not an int division).
puts "Reading Celsius temperature value from data file..."
num = File.read("temperature.dat")
celsius = num.to_f # modification here
farenheit = (celsius * 9/5) + 32
puts "Saving result to output file 'faren_temp.out'"
fh = File.new("faren_temp.out", "w")
fh.puts farenheit
fh.close
faren_temp.out
73.4
How about:
puts "Reading Celsius temperature value from data file..."
farenheit = 0.0
File.open("temperature.dat","r"){|f| farenheit = (f.read.to_f * 9/5) + 32}
puts "Saving result to output file 'faren_temp.out'"
File.open("faren_temp.out","w"){|f|f.write "#{farenheit}\n"}
精彩评论