《python语言程序设计》2018版第7章第06题代数:平方根 设计一个名为QuadraticEquation类
类代码部分
class QuadraticEquation:def __init__(self, a, b, c):self.a = aself.b = bself.c = cdef set_a(self, a):self.a = adef get_a(self):return self.adef set_b(self, b):self.b = bdef get_b(self):return self.bdef set_c(self, c):self.c = cdef get_c(self):return self.cdef 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_num1return root_num2 / (2 * self.a)def get_root2(self):root_num1 = pow(QuadraticEquation.get_discrimination(self), 0.5)root_num2 = -self.b - root_num1return 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 codedef 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)