在这个简单的Python程序中,我们需要求一个三边形的面积。这是一个初级Python程序。
要理解这个例子,您应该了解以下 Python 编程主题
这是一个用 Python 求三角形面积的简单程序。三角形是一个有三条边的形状。为了求三角形的面积,我们使用海伦公式。海伦公式定义为 **(s*(s-a)*(s-b)*(s-c))** 的平方根。其中
要应用此公式,我们必须先求半周长“**s**”。为此,我们使用公式 **s = (a + b + c) / 2**,然后将半周长代入海伦公式。我们使用 Python 中的算术运算符来完成此操作。为了将此逻辑应用于这个初级 Python 程序,我们必须从用户那里获取三角形的边长,并应用半周长公式。然后,利用半周长,我们使用海伦公式。最后,使用 Python 语言中的 print 函数打印结果。
步骤 1:使用 Python 编程中的 input 函数从用户那里获取三角形的边长,并使用 float 数据类型将 Python 字符串转换为浮点数。
步骤 2:使用公式 **(a + b + c) / 2** 计算半周长,其中 **a、b、c** 是三角形的边。
步骤 3:使用海伦公式 "**(s*(s-a)*(s-b)*(s-c)) ** 0.5**" 计算三角形的面积,其中 0.5 在 Python 程序中用于代替平方根。
步骤 4:使用 0.2 精度的浮点数据类型打印结果,即三角形面积。
a = float(input('Enter the first side: '))
b = float(input('Enter the second side: '))
c = float(input('Enter the third side: '))
s = (a + b + c) / 2 # semi perimeter calculation in python
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 # heron's formula apply to find area
print ('The area of the triangle is %0.2f' % area)
Enter the first side: 20 Enter the second side: 20 Enter the third side: 20 The area of the triangle is 96.82