我的二次方程求解器程序(Python 3)没有给我正确的方程解



我的代码是

#Import the module
from math import sqrt
#Using while loop statement to make the program not finish before the user close the program.
while True:
#Print out the introduction message, and get the input value to solve the quadratic equation.
    print("ax^2+bx+c=0의 꼴로 된 방정식을 풀 수 있습니다. a, b, c의 값을 차례대로 입력하세요.")
    a = input("a를 입력하세요 : ")
    b = input("b를 입력하세요 : ")
    c = input("c를 입력하세요 : ")
#Define function that checks whether the input values are natural number or negative number
    def func_num(n):
        if n[0] == '-':
            n = -int(n[1:])
            return n
        else:
            n = int(n)
            return n
#Execute the function for the input value a, b, c
    a = func_num(a); b = func_num(b); c = func_num(c);
#This if statement chekcs whether the solution of the quadratic equation going to be real number or imaginary number.
    if b ** 2 > 4*a*c:
        solution1 = ((sqrt((b ** 2)-(4*a*c)))-b) / (2*a)
        solution2 = (-(sqrt((b ** 2)-(4*a*c)))-b) / (2*a)
    else:
        square_root = sqrt( -(b**2 - 4*a*c) ) + 1j
        solution1 = ( (square_root)  - b  ) / (2*a)
        solution2 = ( -(square_root)  - b  ) / (2*a)
#Prints out the solution of the quadratic equation.
    print("정답은 바로바로... {}, {} 이거다!".format(solution1, solution2))

,它没有给出正确的答案。对于某些方程式,它给出了解决方案的负值(解决方案 * -1),有时甚至解决方案都是错误的(不仅是正/负符号),但有时给出正确的答案。

我该如何改进它,以及代码的哪一部分问题?

您的公式中有一个错误的构想正方形根案例。当您打算乘以1j时,您添加 1j。它应该更改为:

square_root = sqrt( -(b**2 - 4*a*c) ) * 1j
                                      ^

要注意的另一件事:Python完全能够计算一个虚构的平方根 - 您只需要在cmath(复杂的数学)软件包中使用sqrt的版本而不是math软件包:

import cmath
print(cmath.sqrt(4))
print(cmath.sqrt(-4))

这样,您可以避免处理负数的平方根的特殊情况。

最终的改进:事实证明,int函数处理字符串表示负数恰好(例如,尝试int("-5")且效果很好),因此您可以只使用int(a)的调用来替换func_num(a)函数调用,等等。(或更好的是,float(a)将处理浮点数)。

最新更新