我想从我正在学习的书中复制一个代码。这个程序应该找到一个二次函数的平方根,但是一旦我在空闲状态下运行这个模块,我就会得到一个错误。你知道吗
#This is a program to find the square roots of a quadratic function.
import math
def main():
print ("this is a program to find square roots of a quadratic function")
print()
a,b,c = eval(input("enter the value of the coefficients respectively"))
discRoot = math.sqrt( b * b - 4 * a * c )
root1 = ( - b + discRoot ) / 2 * a
root2 = ( - b - discRoot ) / 2 * a
print ("The square roots of the equation are : ", root1, root2 )
print()
main()
我得到以下错误:
Traceback (most recent call last):
File "/home/ubuntu/Desktop/untitled.py", line 21, in <module>
main()
File "/home/ubuntu/Desktop/untitled.py", line 13, in main
discRoot = math.sqrt( b * b - 4 * a * c )
ValueError: math domain error
我到底做错什么了?是因为discRoor值变为负值吗?你知道吗
每当
b * b - 4 * a * c
是一个负数时,math.sqrt(b * b - 4 * a * c)
就会产生一个ValueError
。你知道吗在前面检查,或者使用^{} 模块中的
sqrt
来允许复杂根:或允许复杂根:
相关问题 更多 >
编程相关推荐