简单的二次和线性方程计算器

0 投票
2 回答
696 浏览
提问于 2025-04-17 19:52

我在做一个简单的线性和二次方程计算器时遇到了困难。二次方程的部分可以正常工作,但线性方程却不行。它给出的答案是浮点数,但总是某个数字后面跟着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

2 个回答

0

你应该在用户输入后,立即把 abc 转换成浮点数。

另一种方法是使用 Python 3.x 的除法,这样做会得到你想要的结果,代码如下:

from __future__ import division
0

x = -c/b - 如果c和b都是整数,那么结果也会被四舍五入成整数。

可以这样做:x = -c/float(b)

撰写回答