解二次方程

2024-04-16 15:46:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序似乎没有给我正确的解决方案。有时是,有时不是。我找不到我的错误。有什么建议吗?

import math

a,b,c = input("Enter the coefficients of a, b and c separated by commas: ")

d = b**2-4*a*c # discriminant

if d < 0:
    print "This equation has no real solution"
elif d == 0:
    x = (-b+math.sqrt(b**2-4*a*c))/2*a
    print "This equation has one solutions: ", x
else:
    x1 = (-b+math.sqrt(b**2-4*a*c))/2*a
    x2 = (-b-math.sqrt(b**2-4*a*c))/2*a
    print "This equation has two solutions: ", x1, " and", x2

Tags: andimport程序错误mathsqrt解决方案this
3条回答
# syntaxis:2.7
# solution for quadratic equation
# a*x**2 + b*x + c = 0

d = b**2-4*a*c # discriminant

if d < 0:
    print 'No solutions'
elif d == 0:
    x1 = -b / (2*a)
    print 'The sole solution is',x1
else: # if d > 0
    x1 = (-b + math.sqrt(d)) / (2*a)
    x2 = (-b - math.sqrt(d)) / (2*a)
    print 'Solutions are',x1,'and',x2

给你,每次都应该给你正确的答案!

a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))

d = b**2-4*a*c # discriminant

if d < 0:
    print ("This equation has no real solution")
elif d == 0:
    x = (-b+math.sqrt(b**2-4*a*c))/2*a
    print ("This equation has one solutions: "), x
else:
    x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)
    x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)
    print ("This equation has two solutions: ", x1, " or", x2)

这条线引起了问题:

(-b+math.sqrt(b**2-4*a*c))/2*a

x/2*a被解释为(x/2)*a。您需要更多括号:

(-b + math.sqrt(b**2 - 4*a*c)) / (2 * a)

另外,如果您已经在存储d,为什么不使用它呢?

x = (-b + math.sqrt(d)) / (2 * a)

相关问题 更多 >