gpt4 book ai didi

python - 我如何使用 % 在 Python 中将秒转换为分钟和秒

转载 作者:行者123 更新时间:2023-11-28 21:39:49 33 4
gpt4 key购买 nike

def main():
import math
print('Period of a pendulum')
Earth_gravity = 9.8
Mars_gravity = 3.7263
Jupiter_gravity = 23.12
print(' ')
pen = float(input('How long is the pendulum (m)? '))
if pen < 0:
print('illegal length, length set to 1')
pen = 1
period1 = (2 * 3.14159265359) * math.sqrt(pen / Earth_gravity)
period2 = (2 * 3.14159265359) * math.sqrt(pen / Mars_gravity)
period3 = (2 * 3.14159265359) * math.sqrt(pen / Jupiter_gravity)
print(' ')
print('The period is', round(period1,3))
minutes1 = period1 / 60
minutes2 = period1 / 60
minutes3 = period1 / 60
seconds1 = minutes1 % 60
seconds2 = minutes2 % 60
print('or', round(minutes1,1), 'minutes and', seconds, 'seconds on
Earth')
print(' ')
print('The period is', round(period2,3))
print('or', round(minutes2,1), 'minutes and', seconds, 'seconds on
Mars')
print(' ')
print('The period is', round(period3,3))
print('or', round(minutes3,1), 'minutes and', seconds, 'seconds on
Jupiter')
else:
period1 = (2 * 3.14159265359) * math.sqrt(pen / Earth_gravity)
period2 = (2 * 3.14159265359) * math.sqrt(pen / Mars_gravity)
period3 = (2 * 3.14159265359) * math.sqrt(pen / Jupiter_gravity)
print(' ')
print('The period is', round(period1,3))
minutes1 = period1 // 60
minutes2 = period2 // 60
minutes3 = period3 // 60
seconds1 = minutes1 % 60
seconds2 = minutes2 % 60
seconds3 = minutes3 % 60
print('or', round(minutes1,1), 'minutes and', seconds1, 'seconds on
Earth')
print(' ')
print('The period is', round(period2,3))
print('or', round(minutes2,1), 'minutes and', seconds2, 'seconds on
Mars')
print(' ')
print('The period is', round(period3,3))
print('or', round(minutes3,1), 'minutes and', seconds3, 'seconds on Jupiter')

main()

好的,所以我需要将秒数转换为秒数和分钟数。我不确定如何使用 % 来获取输出中的秒数和分钟数。我需要在此使用//和 %。我对此很陌生,所以如果草率或矫枉过正,我深表歉意。困惑的区域是包含 % 的行。谢谢!

最佳答案

您可以简单地使用 divmod它返回整数除数和模数,非常适合您的情况:

>>> seconds = 1000
>>> minutes, seconds = divmod(seconds, 60)
>>> hours, minutes = divmod(minutes, 60)
>>> days, hours = divmod(hours, 24)
>>> days, hours, minutes, seconds
(0, 0, 16, 40)

似乎您只需要第一行 minutes, seconds = divmod(seconds, 60) 但我想展示如果还有更多转换,如何使用它。 :)

关于python - 我如何使用 % 在 Python 中将秒转换为分钟和秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46269991/

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