首页 > 编程知识 正文

Python 程序:计算三角形面积

时间:2023-11-25 09:12:55 阅读:309054 作者:YBBZ

在这个简单的 python 程序中,我们需要找到一个三边三角形的面积。这是一个初级 python 程序。

要理解这个例子,您应该了解以下 Python 编程主题:

  • Python 语法
  • Python 数据类型
  • Python 运算符

如何在 python 中找到三角形区域?

这是一个寻找三角形面积的简单 python 程序。三角形是有三条边的形状。为了找到三角形的面积,我们使用 Heron 公式。Heron 公式定义为( *s(s-a)(s-b)(s-c)** )的平方根。这里

  • a、b 和 c 是三角形的边。
  • s 是给定三角形的半周长。

在这里应用这个公式,我们必须找到半周长' s 。为此,我们使用公式 s = (a + b + c) / 2 ,然后我们应用苍鹭公式中的半周长。我们使用 python 中的算术运算符来实现。为了在这个初级 python 程序中应用这个逻辑,我们必须接受用户给出的三角形的边,并应用半周长公式。然后用半周长,我们用 heron 公式。并使用 python 语言中的print函数打印结果。

算法

步骤 1:使用 python 编程中的输入函数从用户那里接受三角形的边,并使用 float 数据类型将 python 字符串转换为 float。

第二步:使用公式 (a + b + c) / 2 计算半周长,其中 a、b、c 是三角形的边。

第三步:用 heron 的公式“*(s (s-a)(s-b)(s-c)) 0.5**”计算三角形的面积,这里用的是 0.5 而不是 python 程序中的平方根。

步骤 4:打印结果,因为三角形区域使用的是 0.2 精度浮点数据类型。

Python 源代码

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

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