import math
class FunctionErrorException(Exception):
def __init__(self, error_reason='判别式<0,函数不存在实根'):
Exception.__init__(self, error_reason)
class Equation:
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def getDiscriminant1(self):
d = (self.b) ** 2 - (4 * self.a * self.c)
return d
def getRoot1(self):
if self.getDiscriminant1() >= 0:
x1 = (-self.b + math.sqrt(self.getDiscriminant1())) / 2 * self.a
return x1
else:
raise FunctionErrorException
def getRoot2(self):
if self.getDiscriminant1() >= 0:
x2 = (-self.b + math.sqrt(self.getDiscriminant1())) / 2 * self.a
return x2
else:
raise FunctionErrorException
try:
a = eval(input("a="))
print(a)
b = eval(input("b="))
print(b)
c = eval(input("c="))
print(c)
f = Equation(a, b, c)
# print("判别式:", f.getDiscriminant1())
print("x1:", f.getRoot1())
print("x2:", f.getRoot2())
except FunctionErrorException as reason:
print(reason)
else:
print("程序正常运行,没有捕捉到异常")
设计一个一元二次方程类,并为这个类添加异常处理
最新推荐文章于 2024-07-18 20:05:25 发布