我写了一个程序,你可以找到平均和标准偏差的数据存储在另一个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

最佳答案

由于您的平均值仅基于x[1],所以我假设这些值才是最重要的在这种情况下,只需使用x[1].to_f作为总和:

variance = variance + (x[1].to_f - avg)**2

07-28 11:24