首页 > 编程知识 正文

Python 程序:计算梯形面积

时间:2023-11-25 09:12:54 阅读:309012 作者:LOQE

如何用例子编写 Python 程序求梯形面积和梯形中值?在我们进入实际的 Python 程序寻找梯形面积的例子之前,让我们看看定义和公式

梯形的 Python 面积

如果我们知道高度和两个底长,那么我们可以用下面的公式计算梯形的面积:

面积= (a+b)/2 * h

其中 a 和 b 是两个底,h 是梯形的高度。我们可以用下面的公式计算梯形的中值:

中位数= (a+b) / 2。

如果我们知道中间值和高度,那么我们可以计算梯形的面积为:中间值*高度

寻找梯形面积的 Python 程序

这个 python 程序允许用户输入梯形的两边和高度。使用这些值,这个 Python 程序将计算梯形的面积和梯形的中值。

# Python Program to find Area of a Trapezoid

base1 = float(input('Please Enter the First Base of a Trapezoid: '))
base2 = float(input('Please Enter the Second Base of a Trapezoid: '))
height = float(input('Please Enter the Height of a Trapezoid: '))

# calculate the area
Area = 0.5 * (base1 + base2) * height

# calculate the Median
Median = 0.5 * (base1+ base2)

print("n Area of a Trapezium = %.2f " %Area)
print(" Median of a Trapezium = %.2f " %Median)

以下语句将要求用户输入 base1、base2 和 height 值,并将用户输入值分配给相关变量。如第一个值将赋给 base1,第二个值赋给 base2,第三个值赋给高度

base1 = float(input('Please Enter the First Base of a Trapezoid: '))
base2 = float(input('Please Enter the Second Base of a Trapezoid: '))
height = float(input('Please Enter the Height of a Trapezoid: '))

接下来,我们使用它们各自的公式计算梯形的中值和面积:

# calculate the area
Area = 0.5 * (base1 + base2) * height

# calculate the Median
Median = 0.5 * (base1+ base2)

打印语句将帮助我们打印梯形的中值和面积

print("n Area of a Trapezium = %.2f " %Area)
print(" Median of a Trapezium = %.2f " %Median)

让我们看看程序的输出

Please Enter the First Base of a Trapezoid: 6
Please Enter the Second Base of a Trapezoid: 9
Please Enter the Height of a Trapezoid: 4

 Area of a Trapezium = 30.00 
 Median of a Trapezium = 7.50 

从上面的 Python 截图可以观察到,我们输入的值是 base1 = 6,base2 = 9,height = 4

梯形的面积= 0.5 (基底 1 +基底 2) 高度; 梯形的面积= 0.5 (6+9) 4; 梯形的面积= 0.5 15 4; 梯形面积= 30

梯形的中值= 0.5 (base 1+base 2); 梯形的中值= 0.5 (6 + 9) 梯形的中值= 0.5 * 15 梯形的中值= 7.5

用函数求梯形面积的 Python 程序

这个 python 程序允许用户输入梯形的基底 1、基底 2 和高度。我们将把这些值传递给函数参数来计算梯形的面积。

# Python Program to find Area of a Trapezoid using Functions

def Area_of_a_Trapezoid (base1, base2, height):
    # calculate the area
    Area = 0.5 * (base1 + base2) * height

    # calculate the Median
    Median = 0.5 * (base1+ base2)

    print("n Area of a Trapezium = %.2f " %Area)
    print(" Median of a Trapezium = %.2f " %Median)

Area_of_a_Trapezoid (9, 6, 4)

在这个寻找梯形面积的 Python 程序示例中,首先,我们使用 def 关键字定义了具有三个参数的函数。这意味着,用户将输入梯形的底 1、底 2 和高度。接下来,我们计算梯形的中值和面积,正如我们在第一个例子中所描述的。

注意:我们可以用中的参数调用函数。或者我们可以从 python shell 中调用它。请不要忘记函数参数

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