编写一个 Python 程序,使用半径、周长和直径来计算圆的面积。圆的面积是圆内有多少个平方单位。计算圆面积的标准公式是 A = πr²。
使用半径计算圆面积的 Python 程序
如果我们知道半径,那么我们可以使用公式 A=πr² 来计算圆的面积(其中 A 是圆的面积,r 是半径)。在这个程序中,我们将使用半径来计算圆的面积。
# using Radius
PI = 3.14
radius = float(input(' Please Enter the radius of a circle: '))
area = PI * radius * radius
circumference = 2 * PI * radius
print(" Area Of a Circle = %.2f" %area)
print(" Circumference Of a Circle = %.2f" %circumference)
我们将 pi 定义为全局变量,并赋值为 3.14。这个 Python 程序允许用户输入半径的值。然后,它将根据公式计算圆的面积。示例输出为
Please Enter the radius of a circle: 6
Area Of a Circle = 113.04
Circumference Of a Circle = 37.68
使用周长计算圆面积的 Python 程序
圆的周围距离称为周长。如果你知道周长,那么我们可以使用公式 A= C²⁄ 4π 来计算圆的面积(其中 C 是周长)。
import math
circumference = float(input(' Please Enter the Circumference of a circle: '))
area = (circumference * circumference)/(4 * math.pi)
print(" Area Of a Circle = %.2f" %area)
使用周长计算圆面积的输出
Please Enter the Circumference of a circle: 26
Area Of a Circle = 53.79
首先,我们导入了 math 库,它支持在此编程中使用所有数学函数。在此 Python 示例中,我们可以使用 math.pi 调用 PI 值。
import math
下一行 程序 允许用户输入周长值。
circumference = float(input(' Please Enter the Circumference of a circle: '))
使用周长,此程序将根据公式 A= C²⁄ 4π 计算圆的面积。
使用直径计算圆面积的程序
穿过圆心的圆的距离称为直径。如果我们知道直径,那么我们可以使用公式 A=π/4*D² 来计算圆的面积(D 是直径)。
import math
diameter = float(input(' Please Enter the Diameter of a circle: '))
area1 = (math.pi/4) * (diameter * diameter)
# diameter = 2 * radius
# radius = diameter/2
radius = diameter / 2
area2 = math.pi * radius * radius
print(" Area of Circle using direct formula = %.2f" %area1);
print(" Area of Circle Using Method 2 = %.2f" %area2)
此程序允许用户输入直径值。接下来,它将根据上面显示的公式计算圆的面积。
我们还提到了另一种方法。
直径 = 2 * 半径
半径 = 直径/2
面积 = π * 半径 * 半径

评论已关闭。