以下代码是我用于二次问题求解器的,其中a不能等于0.我目前得到了非常奇怪的答案,似乎无法弄清楚问题。想法?
def descriminant(a, b, c): #Setting input perameters for descriminant
if a>0 or a<0: #If a isnt equal to 0, find descriminant
disc = (b**2-4*a*c) #Defining what descriminant does with disc
if disc>0:
disc1=float(disc)**0.5
return disc1 #returns and allows to be used again instead of print which doesnt allow you to use it again
else:
print("The discriminant must be greater than 0")
else: #if a is equal to 0
print ("A cannot equal 0") #Tell the user a cant equal 0
def quad_form(a, b, c): #Defining quad form w/ input a, b, c
disc2=float(descriminant(a, b, c))
quad_form1=((-1*b) + disc2/float((2*a))) #Defining + forumula for quad form
quad_form2=((-1*b) - disc2/float((2*a))) #Defining - forumula for quad form
return quad_form1, quad_form2
UI=input("Enter the coefficients of a quadratic separated by commas where A is not equal to zero: ") #User Input
a=float(UI[0])
b=float(UI[1])
c=float(UI[2])
print quad_form(a, b, c)
答案 0 :(得分:1)
看起来你要两次取平方根。进入discriminant()
然后进入quad_form()
。你应该删除其中一个。
编辑:
您的quad_form
表达式也是错误的:
quad_form1=((-1*b) + disc3/float((2*a)))
应该是
quad_form1=((-1*b) + disc3)/float((2*a))
或更可读
quad_form1=(-b + disc3)/float(2*a).
同样适用于下一行,
quad_form1=((-1*b) - disc3)/float((2*a))