这是我到目前为止的代码..
#solving a quadratic equation
#finding conjugate pair of imaginary roots if no real roots
import math
import sys
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
try:
# find the discriminant
d = (b**2)-(4*a*c)
if d < 0:
import cmath #importing complex math to find imaginay roots
x1 = (-b-cmath.sqrt(d))/(2*a)
x2 = (-b+cmath.sqrt(d))/(2*a)
print"This equation gives a conjugate pair of imaginary roots: ", x1, " and", x2
elif d == 0:
x = (-b+math.sqrt(d))/(2*a)
print "This equation has one solutions: ", x
else:
x1 = (-b+math.sqrt(d))/(2*a)
x2 = (-b-math.sqrt(d))/(2*a)
print "This equation has two solutions: ", x1, " and", x2
except:
SystemExit
我需要让我的程序对输入非数字数据的用户很健壮。我尝试过使用条件符号(if..elif..else)并尝试异常处理。
我需要程序显示错误消息并提示用户再试一次
HELP
答案 0 :(得分:2)
<强>更新强>
你可能想转
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
到
def get_input(s):
while True:
try:
return float(input('Enter %s: ' % s))
except ValueError:
print 'Error: Invalid Input.'
a = get_input('a')
b = get_input('b')
c = get_input('c')