如何让Ruby程序读取输入数字至输入'end'后计算总和?
Fixing Your Ruby Number Sum Program
Hey there! Let's get your program working correctly. I'll break down the issues in your code first, then show you a couple of simple, working versions tailored for a new programmer. 😊
What was off with your original code?
- You only read input once at the start (
a=gets.to_s), so the loop would keep reusing that first value forever instead of asking for new input each time. - The
while a=a.to_scondition always stays true (non-empty strings count as "true" in Ruby), so the loop would never stop on its own—only if it hits thebreak. - Your
puts ncomes right afterbreak—once youbreakout of the loop, that line never gets to run!
Working Version 1 (Using loop - super easy to read)
sum = 0 loop do # Get input and remove the extra newline character with chomp input = gets.chomp # Stop the loop immediately if user types "end" break if input == "end" # Convert input to integer and add to our total sum sum += input.to_i end # Print the final sum after the loop finishes puts "Total sum: #{sum}"
Working Version 2 (Using while loop if you prefer that style)
If you'd rather stick with a while loop, here's how to structure it properly:
sum = 0 input = "" while input != "end" input = gets.chomp # Only add to sum if the input isn't "end" sum += input.to_i unless input == "end" end puts "Total sum: #{sum}"
Quick tips to remember:
- Use
gets.chompto clean up user input—it removes the hidden newline character that gets added when you press Enter. - Always read new input inside the loop, so the program asks for a fresh value every time it runs through the loop.
- Calculate the sum only when the input is a number, and print the final total after the loop has finished.
内容的提问来源于stack exchange,提问作者Lampob02
相关产品推荐
相关产品推荐

