Python程序计算直角三角形的面积

编写一个Python程序,计算直角三角形的面积,并附带示例。在我们开始编写计算直角三角形面积的Python程序之前,让我们先了解一下定义和公式。

Python直角三角形面积

如果我们知道宽度和高度,就可以使用下面的公式计算直角三角形的面积。

面积 = (1/2) * 宽度 * 高度

使用勾股定理,我们可以轻松地找到直角三角形中未知的边。

c² = a² + b²

周长是边缘的距离。我们可以使用下面的公式计算周长。

周长 = a + b + c

Python程序计算直角三角形的面积

这个Python程序允许用户输入直角三角形的宽度和高度。利用这些值,我们将计算直角三角形的面积和周长。

# Python Program to find Area of a Right Angled Triangle
import math

width = float(input('Please Enter the Width of a Right Angled Triangle: '))
height = float(input('Please Enter the Height of a Right Angled Triangle: '))

# calculate the area
Area = 0.5 * width * height

# calculate the Third Side
c = math.sqrt((width*width) + (height*height))

# calculate the Perimeter
Perimeter = width + height + c

print("\n Area of a right angled triangle is: %.2f" %Area)
print(" Other side of right angled triangle is: %.2f" %c)
print(" Perimeter of right angled triangle is: %.2f" %Perimeter)

Python直角三角形面积输出

Please Enter the Width of a Right Angled Triangle: 7
Please Enter the Height of a Right Angled Triangle: 8

 Area of a right angled triangle is: 28.00
 Other side of right angled triangle is: 10.63
 Perimeter of right angled triangle is: 25.63

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

import math

以下Python语句将允许用户输入直角三角形的宽度和高度。

width = float(input('Please Enter the Width of a Right Angled Triangle: '))
height = float(input('Please Enter the Height of a Right Angled Triangle: '))

接下来,我们计算面积(1/2的值=0.5)。因此,我们使用0.5 * 宽度* 高度作为公式。

Area = 0.5 * width * height

在下一行,我们使用勾股定理C²=a²+b²来计算直角三角形的另一条边,这相当于C = √a²+b²。

c = math.sqrt((width*width) + (height*height))

在这里,我们使用sqrt()函数来计算a²+b²的平方根。sqrt()是一个math函数,用于计算平方根。

在下一行,我们使用以下公式计算周长。

Perimeter = width + height + c

以下print语句将帮助我们打印直角三角形的周长、另一条边和面积。

print("\n Area of a right angled triangle is: %.2f" %Area)
print(" Other side of right angled triangle is: %.2f" %c)
print(" Perimeter of right angled triangle is: %.2f" %Perimeter)

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

这个Python程序允许用户输入直角三角形的宽度和高度。我们将这些值传递给函数参数,以在Python中计算直角三角形的面积。

# Python Program to find Area of a Right Angled Triangle using Functions

import math

def Area_of_a_Right_Angled_Triangle(width, height):
    # calculate the area
    Area = 0.5 * width * height

    # calculate the Third Side
    c = math.sqrt((width * width) + (height * height))
    # calculate the Perimeter
    Perimeter = width + height + c

    print("\n Area of a right angled triangle is: %.2f" %Area)
    print(" Other side of right angled triangle is: %.2f" %c)
    print(" Perimeter of right angled triangle is: %.2f" %Perimeter)

Area_of_a_Right_Angled_Triangle(9, 10)

首先,我们使用def关键字定义了一个带有两个参数的函数。这意味着用户将输入直角三角形的宽度和高度。接下来,我们将计算直角三角形的面积,正如我们在第一个示例中所述。

Python Program to find Area of a Right Angled Triangle using functions