三角形的面积

时间:2021-04-27 19:15:56

标签: python

试图找到三角形的面积,代码非常简单,但是每当我运行代码时,什么都没有发生,甚至打印的第一行(“底边的宽度”)也没有。

print("width of the base") 
width = input()
print("height")
height = input()
variable1 = width*height
area = variable1/2
print("area = {0}".format(area))

1 个答案:

答案 0 :(得分:0)

您所做的仅适用于直角三角形,无论如何,我同意@BuddyBoblll 您需要输入一个数字。 您可以使用 Heron 公式,而不是使用 (height*base/2) 公式,它只需要一两行额外的代码。此外,它会为所有类型的三角形求面积,不限于直角三角形。

# Three sides of the triangle is a, b and c:  
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) 

我为此代码得到的输出是:

Enter first side: 5
Enter second side: 12
Enter third side: 13
The area of the triangle is 30.00
  • 旁注,我正在使用 Python 3.8.0 版本的 mac osx。