0

我在使用简单的线性和二次方程计算器时遇到了困难。二次方有效,但线性无效。它给了我浮点数的答案,但由于某种原因,它总是一些数字,然后是 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
4

2 回答 2

0

您应该在用户输入后立即将a,b和转换c为浮点数。

另一种方法是使用Python 3.x division,它可以按您的预期工作,与

from __future__ import division
于 2013-03-21T11:27:00.917 回答
0

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

做类似的事情x = -c/float(b)

于 2013-03-21T11:28:23.487 回答