Python项目实战:判断三角形类型并精确计算面积(进阶作业)
第1关:判断能否构成三角形
a = float(input())
b = float(input())
c = float(input())
if a + b > c and a + c > b and b + c > a:
p = (a + b + c) / 2
area = (p * (p – a) * (p – b) * (p – c)) ** (1/2)
print('True')
else:
print('False')
第2关:判定是否是直角三角形
# 补充你的代码
a = float(input())
b = float(input())
c = float(input())
if a<0 or a+b<c:
print('False')
elif a*a+b*b==c*c:
print('True')
else:
print('False')
第3关:判定是否是等腰三角形
a = float(input())
b = float(input())
c = float(input())
# 判断是否能构成三角形
if (a + b > c) and (a + c > b) and (b + c > a):
# 判断是否为等腰三角形
if a == b or a == c or b == c:
print("True")
else:
print("False")
else:
print("False")
第4关:计算三角形面积
import math
# 读取输入的三个边长
a = float(input())
b = float(input())
c = float(input())
# 判断是否能构成三角形
if a + b > c and a + c > b and b + c > a:
# 计算半周长
s = (a + b + c) / 2
# 计算三角形面积
area = math.sqrt(s * (s – a) * (s – b) * (s – c))
# 先保留两位小数
rounded_area = round(area, 2)
# 判断小数部分是否只有一位
if int(rounded_area * 10) == rounded_area * 10:
# 小数部分只有一位,保留一位小数
print("{:.1f}".format(rounded_area))
else:
# 小数部分有两位或更多,保留两位小数
print("{:.2f}".format(rounded_area))
else:
print("data error")
第5关:计算三角形外接圆面积
import math
# 读取输入的三个边长
a = float(input())
b = float(input())
c = float(input())
# 判断是否能构成三角形
if a + b > c and a + c > b and b + c > a:
# 计算半周长
s = (a + b + c) / 2
# 计算三角形面积
area = math.sqrt(s * (s – a) * (s – b) * (s – c))
# 计算外接圆半径
radius = (a * b * c) / (4 * area)
# 计算外接圆面积
area_of_circle = math.pi * radius ** 2
# 先保留两位小数
rounded_area = round(area_of_circle, 2)
# 判断小数部分是否只有一位
if int(rounded_area * 10) == rounded_area * 10:
# 小数部分只有一位,保留一位小数
print("{:.1f}".format(rounded_area))
else:
# 小数部分有两位或更多,保留两位小数
print("{:.2f}".format(rounded_area))
else:
print("data error")
作者:摸鱼码