首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >求解二次方程

求解二次方程
EN

Stack Overflow用户
提问于 2013-03-14 07:23:37
回答 9查看 141.3K关注 0票数 16

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

代码语言:javascript
运行
复制
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
EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2013-03-14 07:25:24

这一行导致了问题:

代码语言:javascript
运行
复制
(-b+math.sqrt(b**2-4*a*c))/2*a

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

代码语言:javascript
运行
复制
(-b + math.sqrt(b**2 - 4*a*c)) / (2 * a)

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

代码语言:javascript
运行
复制
x = (-b + math.sqrt(d)) / (2 * a)
票数 22
EN

Stack Overflow用户

发布于 2013-11-15 00:42:17

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

代码语言:javascript
运行
复制
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)
票数 7
EN

Stack Overflow用户

发布于 2018-04-15 08:05:48

接受复杂的根作为解决方案怎么样?

代码语言:javascript
运行
复制
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)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15398427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档