开发者

Loop doesn't terminate upon checking a condition

This loop does not terminate after I type x. I'm really new to Ruby, and so far, it is so much different than wh开发者_开发百科at I learned before - quite interesting,

total = 0
i = 0

while ((number = gets) != "x")
    total += number.to_i
    i += 1
end

puts  "\nAverage: " + (total / i).to_s

Any help is greatly appreciated.


Because gets gives you the newline as well. You need to chomp it.

Try:

while ((number = gets.chomp) != "x")

and you'll see it starts working:

pax> ruby testprog.rb
1
5
33
x

Average: 13
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜