gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:33:40 26 4
gpt4 key购买 nike

车辆行驶的距离可以计算如下:

距离=速度*时间

编写一个程序,询问用户车辆的速度(以英里/小时为单位)以及行驶了多少小时。然后,程序应该使用循环来显示车辆在该时间段内每小时行驶的距离。以下是输出示例:

车辆的速度是多少英里? 40

行驶了多少小时? 3

行驶的小时距离

<小时/>

1:40

2:80

3:120

到目前为止,我已经完成了所有工作,但无法正确显示表格,如第一个小时 (1) 的示例表格所示,它应该从 40 开始,但实际上却从 120 开始。有人可以帮我修复代码吗?忘记提及它应该适用于用户输入的任何值,例如某人在 5 小时内行驶 50 英里/小时

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')

最佳答案

只需更改程序中的两处内容即可。 第一,不需要将for循环内的时间加倍,第二使用变量t而不是time来计算距离。

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

关于python - 使用距离 = 速度 * 时间的循环表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46500343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com