数学域误差二次方程式

时间:2016-09-16 17:03:17

标签: python quadratic

弄清楚除了最后一个错误之外的错误,我现在收到此错误消息,并且无法弄清楚原因,我正在使用我的老师给我们使用的x1和x2的确切公式,我是无法解决错误。

    # Quadratic Formula

# Import the math library to use sqrt() function to find the square root
import math

print("This equation solves for x in the binomial equation: ax^2 + bx + c = 0")

# Get the equation's coefficients and constant from the user
a = 0
while a == 0:
    try:
        a = float(input("Enter the first coefficeint, or a, value:  "))
        if a == 0:
           raise ValueError
    except ValueError:
        print("The value you entered is invalid. Zero is not allowed")
    else:
            break
while (True):
    try:
        b = float(input("Enter the Second coefficeint, or b, value:  "))
    except ValueError:
            print("The value you entered is invalid. only real numbers")
    else:
            break
while (True):
    try:
        c = float(input("Enter the last coefficeint, or c, value:  "))
    except ValueError:
            print("The value you entered is invalid. only real numbers")
    else:
            break
d = (b**2) - (4*a*c)
x1 = ((-b) + math.sqrt(b**2 - 4*a*c)) / (2*a) 
x2 = ((-b) - math.sqrt(b**2 - 4*a*c)) / (2*a)
print("X is: ", x1, " or ", x2)
do_calculation = True
while(do_calculation):
         another_calculation = input("Do you want to perform another calculation? (y/n):")
if(another_calculation !="y"):

该等式在二项式中求解x:ax ^ 2 + bx + c = 0 输入第一个coefficeint或a,值:2 输入第二个coefficeint,或b,值:3 输入最后一个coefficeint或c,值:4 Traceback(最近一次调用最后一次):   文件“/Users/cadenhastie/Downloads/Jtwyp6QuadraticEqnCalc/improvedquadraticeqncalc.py”,第34行,in     x1 =(( - b)+ math.sqrt(b ** 2 - 4 * a * c))/(2 * a) ValueError:数学域错误

1 个答案:

答案 0 :(得分:0)

您有except个语句,没有相应的while True:语句。您通常应该避免使用a = 0 while a == 0: try: a = float(input("Enter the first coefficeint, or a, value: ")) if a == 0: raise ValueError except ValueError: print("The value you entered is invalid. Zero is not allowed") 。代码中的缩进有很多问题

要从错误处理的用户那里获取一个值,您可以执行类似下面的代码。然后,您将为希望用户输入的每个系数重复此操作。您可能希望在某个时刻将其包装在函数中,这样您就不会编写重复的代码。

<div class="container-fluid"> <div class="row"> <div class="col-xs-6 blue"> <div class="container"> <!--content--> </div> </div> <div class="col-xs-6 red"> <div class="container"> <!--content--> </div> </div> </div>