Ruby,大于1000以上的变量不起作用

时间:2017-06-17 12:47:58

标签: ruby

这是我的代码

print("How far in metres are the people away from the spacecraft?")
people = gets.chomp
if people > "600" and (people !~ /\D/)
print ""
else
while !(people > "600" and (people !~ /\D/))
if people < "600" then
print"The people are too close to the launch site, make sure they are 600 metres away from it."
print "How far in metres are the people away from the spacecraft?"
people = gets.chomp
end
if !(people !~ /\D/)
puts "only enter numbers not letters. Please try again:"
people = gets.chomp
end
end
end
print ("The people are away from the launch site.")

我希望当'people'超过600时显示最后一行,但它也必须是一个数字。但最后一行只有在“人”低于1000以上才会出现。感谢所有帮助。 下面有图片 1000

789

2 个答案:

答案 0 :(得分:2)

问题在于您要比较Strings而不是Integers

字符串按字母顺序进行比较,因此"1000" < "700"将为真,因为"1000"按字母顺序排列后会显示在"700"之前。

您想要的是在比较它们之前将字符串转换为整数。像这样:

people = "700"
if people.to_i > 600
  puts "It's greater than 600"
else
  puts "It's less than 600"
end

请注意600周围缺少引号。

答案 1 :(得分:0)

Cast as Integer

如果要将整数作为数值进行比较,则需要首先转换存储在 people 中的字符串。大多数人会告诉您使用String#to_i,但这可能会有问题并导致过多的错误检查代码。最好使用Kernel#Integer,它不仅执行转换,而且还引发了无法强制转换的字符串的异常。例如:

print 'Get integer: '

# Remove newlines and thousands separators, then cast as an integer.
people = Integer gets.chomp.delete ','

if people >= 600
  puts 'Far enough.'
else
  puts 'Not far enough.'
end

这样,如果您输入one thousandx1000x等值,您将获得如下例外:

  

ArgumentError:Integer()的值无效:“x1000x”