【问题标题】:Math Domain Error Quadratic Formula数学域误差二次公式
【发布时间】:2016-09-17 01:53:24
【问题描述】:

找出除了最后一个错误之外的错误,我现在收到此错误消息,但不知道为什么,我正在使用我的老师给我们使用的 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 输入第二个系数,或 b,值:3 输入最后一个 coefficeint 或 c 值:4 回溯(最近一次通话最后): 文件“/Users/cadenhastie/Downloads/Jtwyp6QuadraticEqnCalc/improvedquadraticeqncalc.py”,第 34 行,在 x1 = ((-b) + math.sqrt(b**2 - 4*a*c)) / (2*a) ValueError:数学域错误

【问题讨论】:

  • 请使用完整的错误堆栈跟踪进行编辑
  • 修复你的缩进,这可能会解决问题。
  • 在进行计算之前检查d 是否为正。如果 d 为负数,请考虑抛物线的含义。
  • 想通了,谢谢!

标签: python quadratic


【解决方案1】:

您有 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")

【讨论】:

  • 非常感谢,对这个非常新,它是一个在线课程,所以我尽可能地自学。这很有帮助,让我后来更好地理解错误,现在程序正在运行,只是有一些小缺陷,谢谢!
  • 很抱歉,我直言不讳。试着把你的代码分成小块,让每一块都能工作,然后把它们放在一起。你会到达那里的!
  • 没问题,我知道很难解释简单的事情而不遇到这种方式,我解决了语法错误并且它运行但仍然无法让程序要求第二个和第三个系数一些原因。回到 youtube 我走了!
  • 对这个问题的任何帮助,一旦这个问题得到解决,程序将在数小时后完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多