首页 > 解决方案 > 带有随机库和时间库的 Python 代码语法操作

问题描述

我正在使用python3.6+vscode编译一个程序,但是它显示错误,但我继续调试,没有改善。

希望能得到一些帮助!</p>

下面是代码:

from random import random
from time import perf_counter
DARTS = 1000*1000
hits = 0.0
start = perf_counter
for i in range(1,DARTS+1):
    x, y = random(), random()
    dist = pow(x ** 2 + y ** 2, 0.5)
    if dist <= 1.0:
        hits = hits + 1
pi = 4 * (hits/DARTS)
print("圆周率值是:{}".format(pi))
print("运行时间是:{:.5f}s".format(perf_counter()-start))

标签: pythonpython-3.x

解决方案


如评论中所述,您的第 5 行应如下所示:

  • start = perf_counter()

在你的最后一行中,你从一个数字中减去一个函数:

  • print("运行时间是:{:.5f}s".format(perf_counter()-start))

正确的代码

from random import random
from time import perf_counter
DARTS = 1000*1000
hits = 0.0
start = perf_counter()
for i in range(1,DARTS+1):
    x, y = random(), random()
    dist = pow(x ** 2 + y ** 2, 0.5)
    if dist <= 1.0:
        hits = hits + 1
pi = 4 * (hits/DARTS)
print("圆周率值是:{}".format(pi))
print("运行时间是:{:.5f}s".format(perf_counter()-start))

你在尝试什么:

print("运行时间是:{:.5f}s".format(perf_counter()-perf_counter))


推荐阅读