【问题标题】:Breaking down seconds in a day [duplicate]在一天中分解几秒钟[重复]
【发布时间】:2017-06-08 17:37:09
【问题描述】:

我正在尝试将用户的整数输入分解为 24 小时内的小时、分钟和秒,但在从伪代码到实际代码超过第一小时等式时遇到问题。我希望最终输出在 X 小时、Y 分钟和 Z 秒内:

    day = 86400
    hour = 3600 #1 hour in a day * 60min * 60 sec
    minute = 60
    number = input("Choose a number between 0 and 86400: ")
    while number != 0:
        if number > 0:
            newNumber = number / hour
            number = newNumber

我正在自学编码,所以我希望用一种简单的方法来解决这个问题......我是否走在正确的轨道上?

编辑:我知道这个问题有一个重复的版本,但对我来说,这个问题过于简单(讽刺)。我正在尝试逐步学习,但我非常感谢所有反馈

【问题讨论】:

  • 您需要使用地板除法// 和模数%divmod 但看看stackoverflow.com/questions/775049/python-time-seconds-to-hms
  • #!/usr/bin/env python3; # day = 86400; # not used hour = 3600; minute = 60; number = int(input("Choose a number between 0 and 86400: ")); hours = number // hour; minutes = (number % hour) // 60; seconds = number % minutes; print('hours: {h} minutes: {m} seconds: {s}'.format(h=hours, m=minutes, s=seconds));

标签: python python-3.x


【解决方案1】:

要将用户输入转换为 X 小时 Y 分钟和 Z 秒,这取决于他们输入的内容。如果它是秒,就像上面所说的那样,那么按照上面所说的做,用秒除以 3600 作为你的小时数,然后从开始的数字中减去那个数字。

此外,您似乎正在使用无限 while 循环,因为您并非每次都提示输入。

如果你想做你想做的事,我建议这样做:

number = input("Choose a number between 0 and 86400")
while(number != 0)
    hours = number/3600
    number = number-(hours*3600)
    minutes = number/60
    number = number-(minutes*60)
    seconds = number
    number = 0
print("The Time You Entered was " + str(hours) + " hours, " + str(minutes) + " minutes, and " + str(seconds) " seconds.")

【讨论】:

  • 你不需要那个 while 循环。您应该使用// 地板除法运算符来使其在Python 3 和Python 2 上正常工作。当然,在Python 3 中,您需要使用int() 将输入字符串转换为整数。在 Python 2 中,您确实应该使用 raw_input 并使用 int() 进行转换,而不是使用评估用户输入的不安全 Python 2 input() 函数。有关详细信息,请参阅 SO 老将 Ned Batchelder 的Eval really is dangerous
猜你喜欢
  • 1970-01-01
  • 2010-10-14
  • 2014-03-08
  • 2018-09-24
  • 2012-07-14
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 2011-09-09
相关资源
最近更新 更多