Python 程序计算三角形的面积

如何编写一个Python程序来计算三角形的面积、周长和半周长,并附带示例。在开始计算三角形面积的程序之前,让我们先了解它们背后的定义和公式。

如果我们知道三角形三条边的长度,那么我们可以使用海伦公式来计算三角形的面积。

三角形面积 = √(s*(s-a)*(s-b)*(s-c))

其中 s = (a + b + c )/ 2 (这里 s = 半周长,a、b、c 是三角形的三条边)。

三角形的周长 = a + b + c

Python 程序计算三角形的面积和周长

这个Python程序允许用户输入三角形的三条边。利用这些值,该程序将计算三角形的周长、半周长,然后是三角形的面积。

a = float(input('Please Enter the First side of a Triangle: '))
b = float(input('Please Enter the Second side of a Triangle: '))
c = float(input('Please Enter the Third side of a Triangle: '))

# calculate the Perimeter
Perimeter = a + b + c

# calculate the semi-perimeter
s = (a + b + c) / 2

# calculate the area
Area = (s*(s-a)*(s-b)*(s-c)) ** 0.5

print("\n The Perimeter of Traiangle = %.2f" %Perimeter);
print(" The Semi Perimeter of Traiangle = %.2f" %s);
print(" The Area of a Triangle is %0.2f" %Area)
Python Program to find Area and Perimeter of a Triangle

前三个 Python 语句允许用户输入三角形的三条边:a、b、c。接下来,使用公式 P = a+b+c 计算三角形的周长。

# calculate the Perimeter
Perimeter = a + b + c

接下来,使用公式 (a+b+c)/2 计算半周长。虽然我们可以写成 半周长 = (周长/2),但我们想展示其背后的公式。这就是为什么我们使用标准公式。

s = (a + b + c) / 2

使用海伦公式计算三角形面积

(s*(s-a)*(s-b)*(s-c)) ** 0.5

Python 程序使用函数计算三角形面积

这个 Python 程序允许用户输入三角形的三条边。我们将这三个值传递给函数参数来计算三角形的面积。

# using Functions

import math

def Area_of_Triangle(a, b, c):
    
    # calculate the Perimeter
    Perimeter = a + b + c
    # calculate the semi-perimeter
    s = (a + b + c) / 2

    # calculate the area
    Area = math.sqrt((s*(s-a)*(s-b)*(s-c)))

    print("\n The Perimeter = %.2f" %Perimeter);
    print(" The Semi Perimeter = %.2f" %s);
    print(" The Area is %0.2f" %Area)

Area_of_Triangle(6, 7, 8)
Program to find Area of a Triangle using functions

首先,我们使用以下语句导入了 math 库。这将允许我们使用 数学函数,例如 math.sqrt 函数。

import math

步骤 2:接下来,我们使用 def 关键字定义了带有三个参数的函数。这意味着用户将输入三角形的三条边 a、b、c。

步骤 3:使用海伦公式计算三角形面积:sqrt(s*(s-a)*(s-b)*(s-c));(sqrt() 是 math 库中的数学函数,用于计算平方根。

注意:请在放置括号时小心。如果放错,可能会影响整个计算。