二次方程式的输出不正确

时间:2013-02-12 21:58:28

标签: python python-2.7

用户应该输入A,B和C的值,并获得二次方程的根。在数学上,我的代码给出了错误的答案:

print "Quadratic Formula Calculator!!!"

a = input("Please, enter value for A: ")
b = input("Please, enter value for B: ")
c = input("Please, enter value for C: ")

quad =(b**2 - 4 * a * c)

if quad >= 0:
    quad ** 0.5
    print "quad"

else:
    print "can not compute"

solution1 = (-b + quad) / (2 * a)
solution2 = (b + quad) / (2 * a)

print " Solution 1!!!:", solution1
print " Soultion 2!!!:", solution2

3 个答案:

答案 0 :(得分:4)

你需要这个:

quad = quad ** 0.5

而不只是quad ** 0.5

解决方案是:

(-b + quad) / (2 * a)
(-b - quad) / (2 * a)

如果你不能计算判别式的负值(你可以,答案是一个复杂的共轭值),只需在quad >= 0内移动计算和打印解决方案。

答案 1 :(得分:2)

在m0nhawk的回答的基础上,Hooked的评论(以及Wikipedia)是一种使用专为复数设计的cmath library的方法。

from math import pow
from cmath import sqrt

print "Quadradtic Formula Calculator!!!"
print "Ax²+Bx+C=0"
print "This will attempt to solve for x"

a = input("Please, enter value for A: ")
b = input("Please, enter value for B: ")
c = input("Please, enter value for C: ")

discriminant = sqrt(pow(b,2) - (4 * a * c))

if discriminant.imag != 0:
    print "discriminant is imaginary"
else:
    print " Solution 1!!!:", (-b + discriminant.real) / (2 * a)
    print " Solution 2!!!:", (-b - discriminant.real) / (2 * a)

cmath.sqrt将返回包含.imag.real字段的复数。

答案 2 :(得分:1)

solution1 = (-b + quad) / (2 * a)
solution2 = (b + quad) / (2 * a)

这应该是

solution1 = (-b + quad) / (2 * a)
solution2 = (-b - quad) / (2 * a)

公式是-b加或减根,而不是加或减b加根。