我正在创建一个简短的程序来查找给定数字集的平均值.这是一个程序,其基本结构首先在TI-83上用goto语句编写,所以我对这种事情的正确实践有点不确定.这是有问题的代码:
$sum = 0
$counter = 0
def average
puts "Input another number, or \"end\" to end."
input = gets.chomp
if input == "end"
puts $counter
puts ($sum / $counter).to_f
else
$sum += input.to_f
$counter += 1
puts $counter
average #Here the method is called again, repeating the cycle.
end
end
Run Code Online (Sandbox Code Playgroud)
我不确定如何做到这一点,因为像这样构建的代码点是它可以处理不确定数量的输入,因此它重复性质.