我编写了一个程序,它在单独的 txt 文件中查找数据,然后给出平均值和标准差。它找到了我的平均值,但我得到了标准偏差的错误。想知道有人可以帮我修复我的代码。就是这个:
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
variance = Math.sqrt(variance)
puts variance
我在第 27 行得到一个错误:variance = variance + (x-avg)**2
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>'