计算圆的面积
import math
r = float(input())
area = math.pi * r * r
print('半径是{:.2f}的⚪的面积是{:.6f}'.format(r,area))
print('半径是%.2f的⚪的面积是 %.6f' %(r,area))
温度转换,下面的程序中可以使用eval()函数替换float()函数
tem = input('输入温度,比如83c:')
if tem[-1] in ['c','C']:
f = 1.8*float(tem[0:-1]) + 32
print('{:.5f}F'.format(f))
elif tem[-1] in ['f','F']:
c = (float(tem[0:-1])-32)/1.8
print('%.5fC' %(c))
else:
print('输入错误')
计算Pi的值比较不同数量级下的误差
#计算pi的值
from random import random
from math import sqrt,pi,fabs
import time
for j in range(4,10):
hits = 0
cnt = pow(10,j)
for i in range(1, cnt+1):
x, y = random(), random()
dist = sqrt(x ** 2 + y ** 2)
if dist <= 1.0:
hits = hits + 1
Pi = 4 * (hits/cnt)
print("数量级是 {:-<20}时的Pi值是 {:-<20} 误差是 {:.20f}".format(cnt,Pi,fabs(pi-Pi)/pi))