用于计算三角形面积的 Python 程序

要理解这个例子,你应该具备以下 Python 编程 主题的知识


如果 abc 是三角形的三条边。那么,

s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))

源代码

# Python Program to find the area of triangle

a = 5
b = 6
c = 7

# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))

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

# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

输出

The area of the triangle is 14.70

在此程序中,当给出三条边时,使用 海伦公式 计算三角形的面积。

如果您需要根据用户输入计算三角形的面积,可以使用 input() 函数


另请阅读

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数来计算直角三角形的面积,并四舍五入到小数点后两位。

  • 例如,对于输入 34,输出应为 6.0
  • 原因:直角三角形的面积由 (1/2)*底*高 给出。所以,对于底 = 3 和高 = 4,它是 (1/2)*3*4 = 6.0
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战