首页 > 编程知识 正文

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

时间:2023-11-25 09:12:54 阅读:309016 作者:AEHI

用例子写一个 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.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()是数学函数,用来计算平方根。

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

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 程序

这个 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 关键字定义了带有两个参数的函数。这意味着,用户将输入直角三角形的宽度和高度。接下来,我们计算一个直角三角形的面积,正如我们在第一个例子中描述的那样。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。