szz*_*o24 4 python math dns sqrt
是什么原因引起的问题?
from math import sqrt
print "a : "
a = float(raw_input())
print "b : "
b = float(raw_input())
print "c : "
c = float(raw_input())
d = (a + b + c)/2
s = sqrt(d*(d-a)*(d-b)*(d-c))
print "a+b+c =", a, b, c
print "Distr. =", d*2, "Area =", s
Run Code Online (Sandbox Code Playgroud)
错误:
Traceback (most recent call last):
File "C:/Python27/fájlok/háromszög terület2.py", line 11, in <module>
s = sqrt(d*(d-a)*(d-b)*(d-c))
ValueError: math domain error
Run Code Online (Sandbox Code Playgroud)
问题在于,仅当两个数字之和大于第三个数字时,Heron公式才有效。您需要明确检查。
使用代码实现此目的的一种更好方法是使用异常处理
try:
s = sqrt(d*(d-a)*(d-b)*(d-c))
print "a+b+c =", a, b, c
print "Distr. =", d*2, "Area =", s
except ValueError:
print "Please enter 3 valid sides"
Run Code Online (Sandbox Code Playgroud)
如果您想无障碍地做,try可以按照
delta = (d*(d-a)*(d-b)*(d-c))
if delta>0:
s = sqrt(delta)
print "a+b+c =", a, b, c
print "Distr. =", d*2, "Area =", s
else:
print "Please enter 3 valid sides"
Run Code Online (Sandbox Code Playgroud)
sqrt当您尝试将其与负数一起使用时会出现该错误。sqrt(-4)给出该错误,因为结果是一个复数。
为此,您需要cmath:
>>> from cmath import sqrt
>>> sqrt(-4)
2j
>>> sqrt(4)
(2+0j)
Run Code Online (Sandbox Code Playgroud)