def averager
puts "Put in three numbers. One per line"
num_1 = $stdin.gets.chomp.to_i
num_2 = $stdin.gets.chomp.to_i
num_3 = $stdin.gets.chomp.to_i
half_total = num_1 + num_2 + num_3
total = half_total / 3
end
好的,这是我正在研究的一个平均水平。除了一件事,它工作正常。我希望用户决定他要输入多少个数字。这样,我将不会只限于平均三个数字。谢谢
在这里,用#标记的注释逐行解释。
def averager
puts "How many numbers?" #ask the user how many numbers
numbers = gets.chomp.to_i #get how many numbers
count = 1 #start the count variable for the while loop
half_total = 0 #half_total starts on zero
while(count <= numbers) do #while count is less than or equal to amount of numbers
puts "Enter #{count}° number" #puts "Enter 1°,2° or whatever number"
number = gets.chomp.to_i #get the actual number from the user
half_total = half_total + number #add it to your half total
count = count + 1 #add one to count so we go to the 2°,3° or wtv number
end #end the loop
total = half_total/numbers.to_f #divide half_total by the amount of numbers
#.to_f is used to force float division so decimals don't get cut
puts "The average is: #{total}" #prints the result
total #returns the result in case you don't want to print it
end #end of the function or method
这是通过简单的while循环完成的,就像其他答案所说的那样,如果您仍然对循环的工作方式感到困惑,请查看有关循环的教程http://www.tutorialspoint.com/ruby/ruby_loops.htm
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句