简单二次线性方程计算

2024-04-20 11:31:38 发布

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

我用一个简单的线性和二次方程计算器有困难。二次函数有效,但线性函数不行,它以浮点形式给出了答案,但由于某种原因,它总是一个数,然后是0。例如:如果我想求解2x+13=0,答案将是-7.0,但它应该是-6.5。我想是因为某种原因,它把它(天花板)围起来了。我很确定我在某个地方有语法错误,但我找不到它。 对如何解决这个问题有什么建议吗? 谢谢你的帮助。在

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 a == 0:
    x = -c/b # liner equation
    x = float(x)
    b = float(b)
    c = float(c)
    print "This linear equation has one solution:", x

elif d < 0:
    print "This quadratic equation has no real solution"

elif d == 0:
    x = (-b+math.sqrt(d))/(2*a)
    print "This quadratic equation has one solutions:", x

else:
    x1 = (-b+math.sqrt(d))/(2*a)
    x2 = (-b-math.sqrt(d))/(2*a)
    print "This quadratic equation has two solutions:", x1, "and", x2

Tags: and函数答案线性mathsqrtfloatthis
2条回答

x = -c/b-如果c和b都是整数,则结果也将四舍五入为整数。在

做一些类似x = -c/float(b)

您应该在用户输入之后立即将abc转换为浮动。在

{a1的另一种工作方式是}

from __future__ import division

相关问题 更多 >