puts "enter a number"
x = gets.chomp.to_i
y = 0
while x != 1
y += 1
if x % 2 == 0
x = x / 2
else
x = x*3 + 1
end
print "#{x} "
end
puts "\nThe number of sequence is #{y+1}"
嗨,如果我输入负数或 0,我会得到一个无限循环。如果我的数字是 0 或负数,我如何避免进入循环。
你可以使用x > 1
即
puts "enter a number"
x = gets.chomp.to_i
# if you want to consider negative as positive then x = gets.chomp.to_i.abs
y = 0
while (x > 1)
y += 1
if x % 2 == 0
x = x / 2
else
x = x*3 + 1
end
print "#{x} "
end
puts "\nThe number of sequence is #{y+1}"
希望能帮助到你
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句