我必须编写一个程序,要求用户输入一个数字。 该程序不断询问用户输入号码,直到用户键入“停止” 此时应打印用户输入的数字总和。 我尝试了很多很多事情,但我的想法都没有奏效。 这就是我所拥有的 - 但我可以认为它不正确。我做错了什么?
我只用过 while 循环和数组
total_user_input = []
# As long as the user inputs a number, the program will keep putting Give me a number
# and then adding that number to the total_user_input array.
puts "Give me a number: "
while user_input = gets.chomp.to_i
#add the input to the array total_user_input
total_user_input.push(user_input.to_i)
puts "Give me a number: "
# If the user however types stop, then the loop is broken and we jump down to the
# sum bit - where all of the numbers in the total_user_input array are added together
# and printed. End of program!
if user_input == "stop"
break
end
sum = 0
total_user_input.each { |num|
sum += num
}
puts sum
end
输出不是它应有的样子。
最佳答案
由于其他人已经发现您的代码存在问题,所以让我建议您如何重新组织它。 Ruby 提供了多种执行循环的方法,但您发现主要依靠方法 Kernel#loop 是可取的。和关键字 break . (你会及时了解到,loop
在与枚举器一起使用时特别方便。)
def sum_numbers
tot = 0
loop do
print 'Gimme a number: '
s = gets.chomp
break if s == 'Stop'
tot += s.to_i
end
tot
end
关键字 break
可以选择接受一个参数(尽管我不能说文档中没有提到的原因),在这种情况下它(如果是文字)或其值(如果是变量或方法)由 loop
返回。在这里人们通常会看到
break tot if s == 'Stop'
没有最后一行,tot
。当循环返回 tot
并且这是该方法执行的最后一次计算时,该方法将返回 tot
的最终值。
你可以改写
return tot if user_input == 'Stop'
但我认为大多数编码人员认为最佳实践规定,除非有充分的理由,否则不应从循环内(或嵌套循环内)的方法返回。
一些小的点:
- 我使用
print
而不是puts
来让用户的输入与提示显示在同一行。 - 我使用
s
(表示“字符串”)而不是user_input
,因为它减少了拼写错误的可能性(例如,user_imput
),加快阅读速度,并且(可能是我的一个缺点)看起来更整洁。诚然,s
不是描述性的,但只需记住连续三行代码的含义即可。其他人可能不同意。 - 你可以写,
break if s.downcase == 'stop'
如果你想,比如说,'stop'
或'STOP'
与'Stop'
具有相同的效果。 '23O3'.to_i #=> 23
(这是一个哦,不是零),所以在现实生活中你想要确认'Stop'
或已键入数字的字符串表示形式。
关于ruby - 简单的程序,但非常卡住——Ruby 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57731502/