import math
a=float(input("Enter value for a:"))
b=float(input("Enter value for b:"))
c=float(input("Enter value for c:"))
root1=-b+math.sqrt (b**2-4*a*c)/(2*a)
root2=-b-math.sqrt (b**2-4*a*c)/(2*a)
print(("root1 % 8.2f")%(root1))
print(("root1 % 8.2f")%(root2导入数学是启动我的程序的正确方式,对吗?我一直在第五行得到一个数学域错误?遗漏了什么?谢谢
发布于 2017-01-22 06:41:25
math.sqrt仅适用于非负值。或者在调用math.sqrt之前验证该b**2 - 4*a*c >= 0,或者改用cmath.sqrt来处理复杂的根。
>>> math.sqrt(-4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
>>> cmath.sqrt(-4)
2j请注意,如果使用cmath.sqrt,则打印该值会变得有点复杂,因为没有针对复数值的格式说明符;您需要提取实部和虚部(root1.real和root1.imag),并分别对它们进行格式化。
https://stackoverflow.com/questions/41785270
复制相似问题