我应该写一个程序,提示用户三角形的三边长度,确定三个长度可以形成一个三角形,如果是这样,使用Heron公式计算面积为4位精确度。这就是我到目前为止我不知道在哪里或如何输入数学
import math
def main():
print()
print("Triangle Area Program")
print()
a, b, c = eval(input("Enter three lengths separated by commas: "))
print()
s = (a+b+c) / 2.0
area = sqrt(s*(s-a)*(s-b)*(s-c))
if a > b:
a, b = b, a
if a > c:
a, c = c, a
if b > c:
b, c = c, b
else:
a + b > c
print("A triangle cannot be formed.")
main()
答案 0 :(得分:1)
以下是程序的略微修改版本,用于检查输入是否在一个复合条件表达式中兼容并替换eval
的使用:
import math
def main():
print("\nTriangle Area Program\n")
a, b, c = map(float, input("Enter three lengths separated by commas: ").split(','))
if a + b > c and a + c > b and b + c > a:
s = (a + b + c) / 2.0
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
return round(area, 4) # round area to four decimal places
else:
raise ValueError("The inputs you entered cannot form a triangle")
if __name__ == '__main__':
print(main())
有关尽可能避免eval
的更多信息Why should exec() and eval() be avoided?
答案 1 :(得分:1)
这是你的另一个可能的问题:
import math
def heron(a, b, c):
return 0.25 * math.sqrt((a + (b + c)) * (c - (a - b)) * (c + (a - b)) * (a + (b - c)))
if __name__ == "__main__":
print()
print("Triangle Area Program")
print()
print()
try:
description = "Enter three lengths separated by commas: "
sides = sorted(map(float, input(description).split(',')))
if (sides[1] + sides[2]) < sides[0]:
print("A triangle cannot be formed.")
else:
a, b, c = sides
print("Area of triangle {0}-{1}-{2} is {3:.4f}".format(
sides[0], sides[1], sides[2], heron(a, b, c)))
except Exception as e:
print("Check your input!!!")
print("--> Error: {0}".format(e))
关于此版本的几点说明:
我决定再给你一个版本,因为在评论中你会找到一些关于你的好建议