繁体   English   中英

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

[英]My quadratic equation solver program (Python 3) doesn't give me right solution to the equation

我的代码是

#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))

它没有给出正确的答案。 对于某些方程式,它给出解的负值(solution * -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")可以正常工作),因此您可以将func_num(a)函数调用替换为一个调用到int(a)等(或者更好的是, float(a)将处理浮点数)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM