Python 二次公式无效
Python quadratic formula not working
我正在尝试创建一个简单的程序来求解 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
我犯了什么错误,我该如何改正?
试试这个:
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()
的结果转换为数字类型。
此代码允许您在二次方程中输入三个值和 returns 根或声明没有根:
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)
我正在尝试创建一个简单的程序来求解 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
我犯了什么错误,我该如何改正?
试试这个:
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()
的结果转换为数字类型。
此代码允许您在二次方程中输入三个值和 returns 根或声明没有根:
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)