
Python虽然是计算机编程语言,但是也是可以解决我们实际的生活的问题。在Python中,三角形面积的求取可以使用我们普通三角形面积公式,可以使用if循环,也可以使用海伦公式求取,具体内容请看本文。
方法一:普通面积公式法
1 2 3 4 5 6 7 8 | import math
a=float(input( "请输入三角形的边长a: " ))
b=float(input( "请输入三角形的边长b: " ))
c=float(input( "请输入三角形的边长c: " ))
d=(a+b+c)/2
area=math.sqrt(d*(d-a)*(d-b)*(d-c));
print (str.format( "三角形的三边分别是:a={0},b={1},c={2}" ,a,b,c))
print (str.format( "三角形的面积={0}" ,area))
|
方法二:if循环法
1 2 3 4 5 6 7 8 9 10 | while True:
a = float(input( '输入三角形第一边长:' ))
b = float(input( '输入三角形第二边长: ' ))
c = float(input( '输入三角形第三边长:' ))
if a + b > c and a + c > b and b + c > a:
s = a * b * (1 - ((a ** 2 + b ** 2 - c ** 2) / (2 * a * b)) ** 2) ** 0.5 / 2
print ( '三角形的面积是:%0.2f' % s)
break
else :
print ( '三角形不合法' )
|
方法三:海伦公式法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import math
a = float(input( '依次输入边长:\n' ))
b = float(input())
c = float(input())
p = (a+b+c)/2
x = p*(p-a)*(p-b)*(p-c)
while x<=0 :
print ( '此三边不构成三角形,请重新输入' )
a = float(input( '依次输入边长:\n' ))
b = float(input())
c = float(input())
p = (a+b+c)/2
x = p*(p-a)*(p-b)*(p-c)
s = math.sqrt(x)
print ( '周长:' + str(2*p))
print ( '面积:' + str(s))
|
以上就去Python中求三角形面积的三种方法,大家可以选择自己容易理解的方法进行操作哦~