我试图编写一个程序,当给出两个数字时,它会告诉你女巫更大或是否相等。当我运行下面的代码时,它不适用于任何大于10的数字
print "Please give me your first number."
first_number = gets.chomp
print "Please give me your second number."
second_number = gets.chomp
if first_number == second_number
print "These two are equal."
elsif first_number > second_number
print "Your first number is greater."
elsif first_number < second_number
print "Your second number is greater."
end
答案 0 :(得分:1)
由于gets.comp
的结果是字符串,>
和<
按字母顺序比较字典中的输入。以下是按字母顺序排序的字符串列表:
"1"
"10"
"1300930184"
"2"
"2139182"
"23"
"3"
"aardvark"
"ab"
"avalanche"
"caramel"
您想要的是将字符串转换为整数(整数),然后比较它们。这可以通过例如完成。通过将调用包装成chomp:first_number = Integer(gets.chomp)
答案 1 :(得分:0)
试试这个。
print "Please give me your first number."
first_number = gets.to_i
print "Please give me your second number."
second_number = gets.to_i
puts case first_number <=> second_number
when -1
"Your second number is greater."
when 0
"These two are equal."
when 1
"Your first number is greater."
end
正如其他人所提到的,gets
返回一个字符串,因此对于比较,您必须将字符串转换为整数。另请参阅Integer#<=>。
答案 2 :(得分:0)
解析输入后(如上文其他答案所述)我建议采用这种报告方法,更准确地解决问题,并避免需要进行明确的比较:
if first_number == second_number
puts "The numbers are equal."
else
higher_number = [first_number, second_number].max
puts "#{higher_number} is the higher number."
end
(虽然我承认,在这个问题的层面上获得阵列的最大值可能是一个触手可及。)