我的密码是
#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
。应更改为:另一件需要注意的事情:Python完全能够计算一个虚构的平方根,您只需要使用
cmath
(complex math)包中的sqrt
版本,而不是math
包:这样,就可以避免处理负数平方根的特殊情况。你知道吗
最后一个改进是:
int
函数可以很好地处理表示负数的字符串(例如,试试int("-5")
,它可以很好地工作),因此您可以将func_num(a)
函数调用替换为对int(a)
的调用,等等(或者更好的是,float(a)
,它将处理浮点数)。你知道吗相关问题 更多 >
编程相关推荐