Ruby走时

mgdq6dx1  于 2022-12-22  发布在  Ruby
关注(0)|答案(3)|浏览(95)

我是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
z8dt9xmd

z8dt9xmd1#

这里有一个无限循环:

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大于max_speed时为其分配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"
mrzz3bfm

mrzz3bfm2#

实际上,您并没有对距离求和-距离永远不会超过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
jdgnovmf

jdgnovmf3#

作为风格注解:不要像if/then语句那样使用case语句作为控制流。只使用它们来设置值,并将其他所有内容移出。这可以消除大量冗余代码。例如:

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"

相关问题