我编写了一个程序,您可以在其中找到存储在另一个 txt 文件中的数据的平均值和标准差。但是,每当我运行它时,我都会收到一条错误消息,指出它无法将浮点数转换为数组:
avg_temp.rb:27:in `-': can't convert Float into Array (TypeError)
from avg_temp.rb:27:in `block in <main>'
from avg_temp.rb:26:in `each'
from avg_temp.rb:26:in `<main>'
这是行:
variance = variance + (x-avg)**2
这是程序:
data = File.open("avg_temp.txt", "r+")
contents = data.read
contents = contents.split("\r\n")
#split up array
contents.collect! do |x|
x.split(',')
end
sum = 0
contents.each do |x|
#make loop to find average
sum = sum + x[1].to_f
end
avg = sum / contents.length
puts "The average temperature of Laguardia Airport from 11/97 - 05/11 is:
#{ avg.round(3)}C (Answer is rounded to nearest thousandth place)"
#puts average
variance = 0
contents.each do |x|
variance = variance + (x-avg)**2
end
variance = variance / contents.length
variance = Math.sqrt(variance)
puts variance