一、题目
使用python计算圆周率,并显示计算进度条。
二、代码
from random import random
from math import sqrt
import time
DARTS = 100000000
hits = 0.0
for i in range(1, DARTS+1):
temp=( i / DARTS );
a = '*' * int(temp*100);
b = '.' * int( ((DARTS - i)/DARTS)*100 );
c = temp * 100;
x, y = random(), random()
dist = sqrt(x ** 2 + y ** 2)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits / DARTS)
print("\r{:^3.0f}%[{}->{}],运行时间是: {:5.5}s".format(c, a, b, time.process_time()), end='')
pi = 4 * (hits/DARTS)
print("\nPi值是{}.".format(pi))
"""
==========================
@auther:JingDe
@Date:2022/3/21 0:32
@email:z18691396932@163.com
@IDE:PyCharm
==========================
"""
三、运行结果
18 %[******************->.................................................................................],运行时间是: 137.02s
D:\Software\Anaconda3\python.exe D:/Desktop/PyCharmWork/Demo/work2022-03-21/pi.py
100%[****************************************************************************************************->],运行时间是: 7.6094s
Pi值是3.141408
|