ValueError:数学域错误,不断弹出

ste*_*eve 0 python math

我不时收到此消息。我尝试了所有变体,改变了我使用 sqrt 的方式,一步一步地做……但是这个错误仍然不断出现。这可能是一个新手错误,我没有注意到,因为我是 python 和 ubuntu 的新手。这是我的源代码:-(一个非常简单的程序)

#To find the area of a triangle
a=input("Input the side 'a' of a triangle ")
b=input("Input the side 'b' of a trianlge ")
c=input("Input the side 'c' of a triangle ")
from math import *
s=(a+b+c)/2
sq=(s*(s-a)*(s-b)*(s-c))
area=(sqrt(sq)) 
perimeter=2*(a+b)
print "Area = ", area
print "perimeter=", perimeter
Run Code Online (Sandbox Code Playgroud)

这是我不断收到的错误

Traceback (most recent call last):

   line 8, in <module>

    area=(sqrt(sq))

ValueError: math domain error
Run Code Online (Sandbox Code Playgroud)

Ror*_*ton 5

正如其他人指出的那样,如果三个“边”实际上没有形成三角形,则使用 Heron 公式计算面积将涉及负数的平方根。一个答案显示了如何通过异常处理来处理这个问题。然而,这并没有抓住三个“边”形成一个退化三角形的情况,一个面积为零,因此不是传统的三角形。一个例子是a=1, b=2, c=3. 异常也会等待,直到您尝试计算以找到问题。另一种方法是在计算之前检查值,这将立即发现问题并允许您决定是否接受退化三角形。这是一种检查方法:

a=input("Input the side 'a' of a triangle ")
b=input("Input the side 'b' of a triangle ")
c=input("Input the side 'c' of a triangle ")
if a + b <= c or b + c <= a or c + a <= b:
    print('Those values do not form a triangle.')
else:
    # calculate
Run Code Online (Sandbox Code Playgroud)

这是另一个检查,只有两个不等式而不是传统的三个:

if min(a,b,c) <= 0 or sum(a,b,c) <= 2*max(a,b,c):
    print('Those values do not form a triangle.')
else:
    # calculate
Run Code Online (Sandbox Code Playgroud)

如果要允许退化三角形,请删除检查中的等号。