简体   繁体   English

循环表使用距离=速度*时间

[英]Loop Table using distance = speed * time

The distance a vehicle travels can be calculated as follows: 车辆行驶的距离可以计算如下:

distance = speed * time 距离=速度*时间

Write a program that asks the user for the speed of a vehicle (in miles per hour) and how many hours it has traveled. 编写一个程序,询问用户车辆的速度(每小时英里)以及行驶了多少小时。 The program should then use a loop to display the distance the vehicle has traveled for each hour of that time period. 然后,程序应使用循环来显示该时间段内每个小时车辆的行驶距离。 Here is an example of the output: 这是输出示例:

What is the speed of the vehicle in mph? 车辆的时速是多少英里(mph)? 40 40

How many hours has it traveled? 它旅行了几个小时? 3 3

Hour Distance Traveled 小时行驶距离


1 : 40 1:40

2 : 80 2:80

3 : 120 3:120

I've gotten everything done so far but can't manage to get the table to come out properly, as shown in the example table at the first hour (1) it should start at 40 but instead it starts at 120. Can someone help me fix the code? 到目前为止,我已经完成了所有工作,但是无法设法使该表正确显示,如第一个小时的示例表中所示(1),该表应该从40开始,但是从120开始。有人可以帮忙吗我修复代码? forgot to mention it should work for any value the user enters such as if someone was going 50 mph in 5 hours 忘了说它应该对用户输入的任何值都有效,例如某人在5小时内以50 mph的速度行驶

g = 'y'
while g == 'Y' or g == 'y':
    speed = int(input('Enter mph: '))
    time = int(input('Enter hours: '))

    if time <= 0 or speed <= 0:
        print('Invalid Hours and mph must be greater than 0')
    else:
        for t in range(time):
            distance = speed * time

            print(t + 1,':', distance)
            time = time * 2


        g = 'n'
print('End')

Just change 2 things in your program. 只需在程序中更改2件事即可。 First , there's no need to double the time inside for loop, Second use variable t instead of time to calculate distance. 首先 ,不需要将for循环内的时间加倍, 其次,使用变量t代替时间来计算距离。

g = 'y'
while g == 'Y' or g == 'y':
speed = int(input('Enter mph: '))
time = int(input('Enter hours: '))

if time <= 0 or speed <= 0:
    print('Invalid Hours and mph must be greater than 0')
else:
    for t in range(time):
        distance = speed * (t+1)        // Use t+1 instead of time

        print(t + 1,':', distance)
        # time = time * 2              // No need to double the time


    g = 'n'
print('End')

Input: 
40
3

Output:
(1, ':', 40)
(2, ':', 80)
(3, ':', 120)
End

You need to remove the commas from the print line, and print out the numbers in string format and concat it to the string colon like: 您需要从打印行中删除逗号,并以字符串格式打印数字并将其连接到字符串冒号,例如:

        print(str(t + 1) + ':' + str(distance))

You also need to increment the time by one not multiply by 2 您还需要将时间增加1而不是2

        time = time + 1

Your output distance also can be fixed by calculating it based on t instead of time 输出距离也可以通过基于t而不是时间进行计算来固定

        distance = speed * (t+1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM