我是红宝石的新手,我很难弄清楚如何计算随机旅行时间,直到它超过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
答案 0 :(得分:2)
这里有一个无限循环:
until distance > 1000 do
speed = Random.rand(5...15)
distance = speed * 1
time = time + 1
end
这个循环永远不会起作用,因为最大值distance
可以得到15
,所以我想你想要添加到distance
,而不是替换它;儿子尝试使用+=
代替=
:
until distance > 1000 do
speed = Random.rand(5...15)
distance += speed * 1
time = time + 1
end
每种情况下的所有循环都是一样的。
如何保存最高速度并将其返回到像我这样的语句中 做过吗?
一种方法是在max_speed
大于speed
时添加另一个变量(即speed
)并为其指定max_speed
值:
time = 0
distance = 0
max_speed = 0
until distance > 1000 do
speed = Random.rand(5...15)
max_speed = speed if speed > max_speed
distance += speed * 1
time = time + 1
end
puts "The maximum speed was #{max_speed} miles per hour"
另一种方法是使用数组(虽然我更喜欢第一种选择):
speed = []
until distance > 1000 do
speed << Random.rand(5...15)
distance += speed.last * 1
time = time + 1
end
puts "The maximum speed was #{speed.max} miles per hour"
答案 1 :(得分:0)
你实际上并没有总结距离 - 距离永远不会超过1000
until distance > 1000 do
speed = Random.rand(5...15)
distance = speed * 1 # will never equal more than 15
time = time + 1
end
你可能想要
distance += speed * 1 # not sure why you're multiplying by 1 though
答案 2 :(得分:0)
作为样式注释:不要使用case
语句作为控制流,如if / then语句。只需使用它们来设置值,并将其他所有内容移出。这可以消除大量冗余代码。例如:
time = 0
distance = 0
until distance > 1000 do
speed = case vehicle
when "1" then Random.rand(5...15) #Bicycle
when "2" then Random.rand(20...70) #Car
when "3" then Random.rand(400...600) #Plane
end
distance += speed * 1
time = time + 1
end
puts "The number of hours it took to travel 1000 miles was #{time} hours"