计算三角形的面积

法一:

#计算三角形的面积

a = float(input('输入三角形第一边长:'))
b = float(input('输入三角形第二边长: '))
c = float(input('输入三角形第三边长:'))

while a+b<c or a+c<b or b+c<a:
    print('输入的边不构成三角形,请重新输入:')
    a = float(input('输入三角形第一边长:'))
    b = float(input('输入三角形第二边长: '))
    c = float(input('输入三角形第三边长:'))

s = (a+b+c)/2
area = (s*(s-a)*(s-b)*(s-c))**0.5
print('三角形面积为:%0.2f' % area)

在这里插入图片描述
法二:
将输入加入循环里:

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('三角形不合法')

在这里插入图片描述
法三:加一些输入的限制条件

import math
import unicodedata
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        unicodedata.digit(s)
        return True
    except (TypeError, ValueError):
        pass
    return False

def cal(a, b, c):
    if is_number(a) and is_number(b) and is_number(c):
        a = float(a)
        b = float(b)
        c = float(c)
        if a > 0  and b > 0 and c >0:
            while a+b<=c or a+c<=b or b+c<=a:
                print("输入的边长无法构成三角形")
                a = input('输入三角形边长a: ')
                b = input('输入三角形边长b: ')
                c = input('输入三角形边长c: ')
                cal(a,b,c)
            p = (a+b+c)/2
            area = math.sqrt(p*(p - a)*(p - b)*(p - c))
            print("三角形面积为:%0.2f" % area)
        else:
            print("三角形的边长必须大于0,请输入大于0的数")
    else:
        print('请输入数字类型')

a = input('输入三角形边长: ')
b = input('输入三角形边长: ')
c = input('输入三角形边长: ')
cal(a,b,c)

在这里插入图片描述

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐