首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python二次公式无效

Python二次公式无效
EN

Stack Overflow用户
提问于 2017-05-05 21:14:31
回答 2查看 305关注 0票数 0

我正在尝试创建一个简单的程序,以便为python中的二次方程的根提供唯一答案,但我的代码不起作用。以下是我到目前为止所拥有的:

代码语言:javascript
复制
from math import *
def qf(a, b, c):
    print((-b+sqrt(b*b-4*a*c))/(2*a));
    print((-b-sqrt(b*b-4*a*c))/(2*a));
while(True):
    qf(input("A: "), input("B: "), input("C: "))

以下是我在评估时遇到的错误:

代码语言:javascript
复制
Traceback (most recent call last):
  File "qf.py", line 6, in <module>
    qf(input("A: "), input("B: "), input("C: "))
  File "qf.py", line 3, in qf
    print((-b+sqrt(b*b-4*a*c))/(2*a));
ValueError: math domain error

我犯了什么错误,怎么改正呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-05 21:28:26

试试这个:

代码语言:javascript
复制
from math import *
def qf(a, b, c):
    if b*b < 4*a*c:
        print("cannot compute qf({}, {}, {})".format(a, b, c))
        return
    print((-b+sqrt(b*b-4*a*c))/(2*a));
    print((-b-sqrt(b*b-4*a*c))/(2*a));
while(True):
    qf(float(input("A: ")), float(input("B: ")), float(input("C: ")))

您需要确保不将负值传递给sqrt()。此外,您应该将input()的结果转换为数字类型。

票数 2
EN

Stack Overflow用户

发布于 2019-06-25 21:57:24

此代码允许您在四分式等式中输入三个值,并返回根或没有根的状态:

代码语言:javascript
复制
import math
def solveQuadratic(a,b,c):
    dis = discriminant(a,b,c)
    if dis < 0:
        print('no real roots')
    else:
        sqdis = math.sqrt(dis)
        topOne = -b+sqdis
        B = 2*a
        firstRoot = topOne/B
        firstRoot = str(firstRoot)
        print ('the first root is: '+firstRoot)
        topTwo = -b-sqdis
        B = 2*a
        secondRoot = topTwo/B
        secondRoot = str(secondRoot)
        print ('the second root is: '+secondRoot)
def discriminant(a,b,c):
    fp = b*b
    ac = a*c
    sp = -4*ac
    dis = fp+sp
    return (dis)

print('enter first coefficient')
a = input()
a = int(a)
print('enter second coefficient')
b = input()
b = int(b)
print('enter the constant')
c = input()
c = int(c)
solveQuadratic(a,b,c)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43813831

复制
相关文章

相似问题

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