【问题标题】:python3 time result not correctpython3时间结果不正确
【发布时间】:2017-02-08 03:04:15
【问题描述】:

我得到了以下代码。我在其中添加了 time() 以让我计算用户遇到问题和用户输入数据之间的延迟。

但结果时间并不总是正确的,我不知道为什么。

from time import time
from random import randint

a = randint(0,1000)
b = randint(0,1000)
cor_answer = a+b
usr_answer = int(input("what is "+str(a)+"+"+str(b)+"? \n"))

start = time()
if usr_answer == cor_answer:
    print("yes you are correct!")
else:
    print("no you are wrong!")
end = time()

elapsed = end - start

print("That took you "+str(elapsed)+" seconds. \n")

这是从命令行执行的结果:

~/math_quiz/math_quiz$ python3 math_quiz.py 
what is 666+618? 
1284
1284
1284
yes you are correct!
That took you 4.291534423828125e-05 seconds. 

但是 time() 显然有效,因为如果我在 IDLE 中运行它,我会得到:

>>> start = time()
>>> time()-start
13.856008052825928

所以我不确定为什么从 cmdline 执行会得到不同的结果。

谢谢

【问题讨论】:

  • 检查答案。它是 4.291534423828125e-05。它太小了,无法在运行之间给出有意义的分辨率。

标签: python-3.x time


【解决方案1】:

您的代码当前在用户输入答案后启动计时器

您需要将此代码start = time() 放在usr_answer = int(input("what is "+str(a)+"+"+str(b)+"? \n")) 之前

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多