gpt4 book ai didi

ruby-on-rails - 如何将 float 转换为 ruby​​ 中的数组?

转载 作者:太空宇宙 更新时间:2023-11-03 16:28:54 25 4
gpt4 key购买 nike

我编写了一个程序,您可以在其中找到存储在另一个 txt 文件中的数据的平均值和标准差。但是,每当我运行它时,我都会收到一条错误消息,指出它无法将 float 转换为数组:

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

关于ruby-on-rails - 如何将 float 转换为 ruby​​ 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19503977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com