python创建类Triangle求三角形面积和周长

创建类Triangle,计算三角形的周长和面积,并创建两个实例进行检测。


import math
class Triangle(object):
    def __init__(self,a,b,c):
        self.a = a
        self.b = b
        self.c = c
    
    # 获取面积
    def get_area(self): 
        # 三角形面积公式,根据三边
        return 1/4 * math.sqrt((self.a + self.b + self.c) * (self.a + self.b -self.c) 
                               * (self.a + self.c - self.b) * (self.b + self.c - self.a))
    
    # 获取周长
    def get_permeter(self):
        return self.a + self.b + self.c
    
trig = Triangle(2,3,4)
area = trig.get_area()
permeter = trig.get_permeter()
print("面积: {:.2f},周长: {}".format(area,permeter))

结果:

img

如果觉得答案对你有帮助,请点击下采纳,谢谢~


class Triangle:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def do(self):
        s = (self.a + self.b + self.c) / 2
        if self.a > 0 and self.b > 0 and self.c > 0 and self.a + self.b > self.c and self.a + self.c > self.b and self.c + self.b > self.a:
            import math
            print("S=",
                  math.sqrt(s * (self.a + self.b - self.c) * (self.a + self.c - self.b) * (self.b + self.c - self.a)))
            print("L=", self.a + self.b + self.c)
        else:
            print('不能构成三角形')

a=Triangle(7,4,5)
b=Triangle(3,3,6)
a.do()
b.do()