【发布时间】:2020-01-03 23:44:28
【问题描述】:
我必须编写一个要求用户输入数字的程序。 程序不断向用户询问一个数字,直到用户键入“停止” 此时应打印用户输入的数字总和。 我尝试了很多很多东西,但我的想法都没有奏效。 这就是我所拥有的——但我可以认为它是不正确的。我做错了什么?
我只用过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
输出不是应有的。
【问题讨论】:
-
这段代码中的缩进确实不一致,并且 cmets 被分解,所以它们的一部分看起来像代码。解决了这个问题,但请尽量保持您的示例尽可能干净。它有助于我们理解问题。
-
提示:你会得到
gets.chomp.to_i的输出是"stop"吗? -
关于 SO 的最佳做法是不要将第一个答案标记为立即接受,因为其他人可能会提供替代解决方案。
-
进一步了解@lacostenycoder 的观点,请参阅this recent question 上的cmets。
标签: ruby loops iteration interactive