类代码部分
class QuadraticEquation:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def set_a(self, a):
self.a = a
def get_a(self):
return self.a
def set_b(self, b):
self.b = b
def get_b(self):
return self.b
def set_c(self, c):
self.c = c
def get_c(self):
return self.c
def get_discrimination(self):
return pow(self.b, 2) - (4 * self.a * self.c)
def get_root1(self):
root_num1 = pow(QuadraticEquation.get_discrimination(self), 0.5)
root_num2 = -self.b + root_num1
return root_num2 / (2 * self.a)
def get_root2(self):
root_num1 = pow(QuadraticEquation.get_discrimination(self), 0.5)
root_num2 = -self.b - root_num1
return root_num2 / (2 * self.a)
def get_judge_num(self):
a_num = QuadraticEquation.get_discrimination(self)
b_num1 = QuadraticEquation.get_root1(self)
b_num2 = QuadraticEquation.get_root2(self)
if a_num == 0:
return f"The root is {b_num1 or b_num2}"
elif a_num > 0:
return "The roots are {:.5f} and {:.5f}".format(b_num1, b_num2)
else:
return "The equation has no real roots"
main部分
def main():
con_method1 = exCode07.QuadraticEquation(1, 3, 1)
con_method2 = exCode07.QuadraticEquation(1, 2, 1)
con_method3 = exCode07.QuadraticEquation(1, 2, 3)
print(f"#1 method result is {con_method1.get_judge_num()}")
print(f"#2 method result is {con_method2.get_judge_num()}")
print(f"#3 method result is {con_method3.get_judge_num()}")
main()
顺便这个是4.1题的代码,只不过经过我多次学习用的
04.01 code
def roots(a, b, c):
con_method = pow(b, 2) - (4 * a * c)
r1 = (-b + pow(con_method, 0.5)) / (2 * a)
r2 = (-b - pow(con_method, 0.5)) / (2 * a)
if con_method == 0:
print(f"The root is {r1 or r2}")
elif con_method > 0:
print("The roots are {:.5f} and {:.5f}".format(r1, r2))
else:
print("The equation has no real roots")
roots(1,3,1)
roots(1,2,1)
roots(1,2,3)
标签:06,get,python,self,2018,root,QuadraticEquation,def,con
From: https://blog.csdn.net/m0_37228426/article/details/141284705