2015-02-08 61 views
-5
import math 

print ("f(x) = ax2 + bx + c") 

# #Get a, b and c from user 

aval = float(input("Please Enter (a) value: ")) 
bval = float(input("Please Enter (b) value: ")) 
cval = float(input("Please Enter (c) calue: ")) 

# #Find roots 
# THIS IS WERE IT GOES WRONG 

root1 = (-(bval) + math.sqrt(bval**2 - 4*aval*cval)) 
root2 = (-(bval) - math.sqrt(bval**2 - 4*aval*cval)) 

#Check discriminant 

discrim = float((bval**2)-(4*aval*cval)) 

if float(discrim > 0): 
    print ("Roots at: ",roo1,root2) 

elif float(discrim == 0): 
    print ("Only one real root: ", root1, root2) 

else: 
    print ("No real Roots.") 
+3

不是随意添加一些东西,而是添加一个实际问题。 *至少*告诉我们你给你的程序给了什么输入,以及你从它得到了什么样的** full **错误信息。作为额外的奖励,*期望的输出*会很好。 – 2015-02-08 00:50:03

+0

您正试图获得负数的平方根,因此_math域error_。 – rodrigo 2015-02-08 00:53:39

+0

他可能试图计算负数的平方根,这会提示“数值错误:数学域错误”。 – bconstanzo 2015-02-08 00:54:35

回答

0

正如其他人所说,你应该打电话sqrt()只有适当的价值。

所以做的更好

... 

#Check discriminant 

discrim = float((bval**2)-(4*aval*cval)) 

if float(discrim >= 0): 
    # now it is ok to calculate the roots... 
    root1 = - bval + math.sqrt(discrim) 
    root2 = - bval - math.sqrt(discrim) 

    if float(discrim > 0): 
     print ("Roots at:", root1, root2) 
    else: 
     print ("Only one real root:", root1, root2) 
else: 
    print ("No real roots.") 

这种方式,我们确信,我们可以调用sqrt

+0

感谢这有所帮助 – 2015-02-08 17:37:59

0

您在计算sqrt(bval**2 - 4*aval*cval),其中parens中的所有参数都是用户提供的。如果您输入的内容会导致参数为负数,则会发生错误。