在python中使用while循环计算周长和面积



编写一个程序,计算圆的周长和表面积。创建一个表格,以0.5厘米为增量打印半径从1厘米到20厘米(含(的周长和表面积。

我试过这个

import math
def main():
# inputs
radius = int(20)
i = float
# loop
while i in range(1, radius+1):
a = math.pi * radius ** 2
c = 2 * math.pi * radius
print(f'{i:3d}{a:13.2f}{c:15.2f}')
break
main()

但当我运行程序时,什么也没发生。

您可以将radius初始化为1并循环,直到它大于20,在每次迭代结束时将其递增0.5

def main():
radius = 1
while radius <= 20:
a = math.pi * radius ** 2
c = 2 * math.pi * radius
print(f'{a:13.2f}{c:15.2f}')
radius += .5
from numpy import pi
from numpy import arange
def main():
# Python makes it easy to directly loop over different radius values
# no need to manually check conditions (tip: have a look at iterators)
for radius in arange(0.5, 20.0, 0.5): 
# directly assigns value to radius
# instead of the OPs checking of i in the while loop. No need for i at all
a = pi * radius**2
c = 2 * pi * radius
print(f'{radius}{a:13.2f}{c:15.2f}')
# no need for "break"
main() # call to function

最新更新