我正在尝试创建一个简单的程序,以便为python中的二次方程的根提供唯一答案,但我的代码不起作用。以下是我到目前为止所拥有的:
from math import *
def qf(a, b, c):
print((-b+sqrt(b*b-4*a*c))/(2*a));
print((-b-sqrt(b*b-4*a*c))/(2*a));
while(True):
qf(input("A: "), input("B: "), input("C: "))以下是我在评估时遇到的错误:
Traceback (most recent call last):
File "qf.py", line 6, in <module>
qf(input("A: "), input("B: "), input("C: "))
File "qf.py", line 3, in qf
print((-b+sqrt(b*b-4*a*c))/(2*a));
ValueError: math domain error我犯了什么错误,怎么改正呢?
发布于 2017-05-05 21:28:26
试试这个:
from math import *
def qf(a, b, c):
if b*b < 4*a*c:
print("cannot compute qf({}, {}, {})".format(a, b, c))
return
print((-b+sqrt(b*b-4*a*c))/(2*a));
print((-b-sqrt(b*b-4*a*c))/(2*a));
while(True):
qf(float(input("A: ")), float(input("B: ")), float(input("C: ")))您需要确保不将负值传递给sqrt()。此外,您应该将input()的结果转换为数字类型。
发布于 2019-06-25 21:57:24
此代码允许您在四分式等式中输入三个值,并返回根或没有根的状态:
import math
def solveQuadratic(a,b,c):
dis = discriminant(a,b,c)
if dis < 0:
print('no real roots')
else:
sqdis = math.sqrt(dis)
topOne = -b+sqdis
B = 2*a
firstRoot = topOne/B
firstRoot = str(firstRoot)
print ('the first root is: '+firstRoot)
topTwo = -b-sqdis
B = 2*a
secondRoot = topTwo/B
secondRoot = str(secondRoot)
print ('the second root is: '+secondRoot)
def discriminant(a,b,c):
fp = b*b
ac = a*c
sp = -4*ac
dis = fp+sp
return (dis)
print('enter first coefficient')
a = input()
a = int(a)
print('enter second coefficient')
b = input()
b = int(b)
print('enter the constant')
c = input()
c = int(c)
solveQuadratic(a,b,c)https://stackoverflow.com/questions/43813831
复制相似问题