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

2024-10-01 09:42:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

好的,我需要把秒转换成秒和分。我不知道如何使用%来获得输出中的秒和分。我需要在这里使用//and%。我在这方面很新,所以我道歉,如果它是草率或过度。混乱的区域是包含%的行。谢谢您!在


Tags: ortheismathsqrtgravityperiodseconds
2条回答

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

>>> 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),但是我想展示一下如果有更多的转换,如何使用它。:)

整数将向下舍入到最接近的整数。%或模运算符只报告除法运算的剩余部分。在

所以135%60返回15。这是因为60比135大两倍,而剩下的15比60少。60到135的两次运算不会返回,因此需要使用标准除法运算符来查找该值。在

您可以除以60得到分钟,然后还可以使用模运算符返回剩余的秒数。在

time = 135

minutes = time / 60
seconds = time % 60

print minutes
print seconds

退货

^{pr2}$

相关问题 更多 >