我尝试在基于用户输入的范围之间生成随机数,问题是程序在运行时似乎存储了指定范围之外的数字。在下面的示例中,我输入了8
和'将ex_val'返回247.5
。 8
不应该给我任何高于170.001
的东西,我在哪里错了?
class Example
print "Input number between 1-12: "
example_range = gets.chomp
if example_range = 11 || 12
ex_val = rand(212.502..255)
elsif example_range = 9 || 10
ex_val = rand(170.002..212.501)
elsif example_range = 7 || 8
ex_val = rand(127.5..170.001)
elsif example_range = 5 || 6
ex_val = rand(84.999..127.499)
elsif example_range = 3 || 4
ex_val = rand(42.499..84.998)
elsif example_range = 1 || 2
ex_val = rand(0..42.498)
end
puts ex_val.round(1)
end
我尝试使用'当'而不是像这样的if语句:
case example_range
when 11, 12
ex_val = rand(212.502..255)
...
end
但似乎总是返回原始输入。
答案 0 :(得分:0)
您的代码不起作用有两个原因:
=
是一项任务,而不是像Andrey Deineko已经解释过的那样的比较。gets.chomp
返回一个不是整数的字符串。由于您尝试将用户的输入与整数进行比较,因此不符合条件。此外,我想建议将if ..elsif
块重构为哈希查找。 IMO使其更易于阅读,理解和维护:
fraction = (255/6.to_f)
ranges = {
'1' => ((fraction * 0)...(fraction * 1)),
'2' => ((fraction * 0)...(fraction * 1)),
'3' => ((fraction * 1)...(fraction * 2)),
'4' => ((fraction * 1)...(fraction * 2)),
'5' => ((fraction * 2)...(fraction * 3)),
'6' => ((fraction * 2)...(fraction * 3)),
'7' => ((fraction * 3)...(fraction * 4)),
'8' => ((fraction * 3)...(fraction * 4)),
'9' => ((fraction * 4)...(fraction * 5)),
'10' => ((fraction * 4)...(fraction * 5)),
'11' => ((fraction * 5)..(fraction * 6)),
'12' => ((fraction * 5)..(fraction * 6))
}
print 'Input number between 1-12: '
range = gets.chomp
puts rand(ranges[range]).round(1)