我的程序似乎没有给我正确的解决方案。有时会,有时不会。我找不到我的错误。有什么建议吗?
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
发布于 2013-03-14 07:25:24
这一行导致了问题:
(-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)
发布于 2013-11-15 00:42:17
给你,每次都会给你正确的答案!
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)
发布于 2018-04-15 08:05:48
接受复杂的根作为解决方案怎么样?
import math
# User inserting the values of a, b and c
a = float(input("Insert coefficient a: "))
b = float(input("Insert coefficient b: "))
c = float(input("Insert coefficient c: "))
discriminant = b**2 - 4 * a * c
if discriminant >= 0:
x_1=(-b+math.sqrt(discriminant))/2*a
x_2=(-b-math.sqrt(discriminant))/2*a
else:
x_1= complex((-b/(2*a)),math.sqrt(-discriminant)/(2*a))
x_2= complex((-b/(2*a)),-math.sqrt(-discriminant)/(2*a))
if discriminant > 0:
print("The function has two distinct real roots: ", x_1, " and ", x_2)
elif discriminant == 0:
print("The function has one double root: ", x_1)
else:
print("The function has two complex (conjugate) roots: ", x_1, " and ", x_2)
https://stackoverflow.com/questions/15398427
复制相似问题