2

用户应该输入 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
4

3 回答 3

4

你需要这个:

quad = quad ** 0.5

而不仅仅是quad ** 0.5.

解决方案是:

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

如果您无法计算判别式的负值(可以,答案将是复共轭值),只需将解决方案的计算和打印移到quad >= 0.

于 2013-02-12T21:59:54.720 回答
2

基于 m0nhawk 的回答,Hooked 的评论(和Wikipedia)在这里是一种使用为复数设计的cmath 库的方法。

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字段的复数。

于 2013-02-12T22:39:21.537 回答
1
solution1 = (-b + quad) / (2 * a)
solution2 = (b + quad) / (2 * a)

这应该是

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

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

于 2013-02-12T22:05:06.057 回答