我是ruby的新手,我很难弄清楚如何计算一个随机旅行时间,直到它通过1000英里。到目前为止,我不明白为什么它不输出结果,它只是停留在用户输入。请帮助
def travel_time()
printf "Pick a vehicle: \n"
printf "1. Bicycle \n"
printf "2. Car \n"
printf "3. Jet Plane \n"
puts "Choose 1-3: \n"
vehicle = gets.chomp
case vehicle
when "1"
#Bicycle: 5-15 miles per hour
time = 0
distance = 0
until distance > 1000 do
speed = Random.rand(5...15)
distance = speed * 1
time = time + 1
end
puts "The number of hours it took to travel 1000 miles was #{time} hours"
when "2"
#Car: 20-70 miles per hour
time = 0
distance = 0
until distance > 1000 do
speed = Random.rand(20...70)
distance = speed * 1
time = time + 1
end
puts "The number of hours it took to travel 1000 miles was #{time} hours"
when "3"
#Jet Plane: 400-600 miles per hour
time = 0
distance = 0
until distance > 1000 do
speed = Random.rand(400...600)
distance = speed * 1
time = time + 1
end
puts "The number of hours it took to travel 1000 miles was #{time} hours"
end
end
travel_time
3条答案
按热度按时间z8dt9xmd1#
这里有一个无限循环:
这个循环永远不会结束,因为
distance
可以得到的最大值是15
,所以我认为你应该添加到distance
,而不是替换它;儿子尝试使用+=
而不是=
:在每种情况下,所有循环也是如此。
如何保存最大速度并像我所做的那样在语句中返回它?
一种方法是添加另一个变量(例如
max_speed
),并在speed
大于max_speed
时为其分配speed
值:另一种方法是使用数组(尽管我更喜欢第一种选择):
mrzz3bfm2#
实际上,您并没有对距离求和-距离永远不会超过1000
你可能想
jdgnovmf3#
作为风格注解:不要像if/then语句那样使用
case
语句作为控制流。只使用它们来设置值,并将其他所有内容移出。这可以消除大量冗余代码。例如: