[英]Math Domain Error Quadratic Formula
找出了除上一个错误以外的错误,我现在收到此错误消息,无法弄清原因,我使用的是我老师给我们使用的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追溯(最近一次通话最近):文件“ /Users/cadenhastie/Downloads/Jtwyp6QuadraticEqnCalc/improvedquadraticeqncalc.py”,第34行,x1 =((-b)+ math.sqrt(b ** 2-4-* a * c))/(2 * a)ValueError:数学域错误
您有try
语句,没有相应的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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.