2017-02-26 55 views
-3

在python 3.5中使用此代码的'二次公式';有什么办法可以打印ValueError的东西吗?

def quad(a,b,c): 
    d = (b**2) - (4*a*c) 
    num1 = (-b+math.sqrt(d))/(2*a) 
    num2 = (-b-math.sqrt(d))/(2*a) 
    print ("Your solutions are", num1, "and", num2) 

的代码工作正常,但有什么办法,我要补充的是显示(“数学错误”)的打印功能,当NUM1和NUM2值显示为“ValueError异常:数学域误差”

进出口寻找这样的事情...

if num1 or num2 = ValueError: # I can't figure out how to 'word' this 
    print ("Math Error") 
+0

你ç应该测试'd <0'吗?甚至打印那么复杂的解决方案? – LutzL

回答

0

只需使用一个平均正常的异常处理程序

import sys 

def quad(a,b,c): 
    try: 
     d = (b**2) - (4*a*c) 
     num1 = (-b+math.sqrt(d))/(2*a) 
     num2 = (-b-math.sqrt(d))/(2*a) 
     print ("Your solutions are", num1, "and", num2) 
    except ValueError as e: 
     print("Math error", e, file=sys.stderr) 
相关问题