python - 除以0时,我希望它打印给定的文本

标签 python if-statement math printing error-handling

import math

def roots4(outfile,a,b,c):
    """Prints the solutions of 'x' for equation ax² + bx + c = 0 """
    d = b * b - 4 * a * c
    if a == 0 and b == 0 and c == 0:
        print "X = All complex/real numbers."

    if c != 0:
        print "X = No real solutions."

    e = (-c / (b))
    if a == 0 and b > 0 < c:
        print "There's only one solution: " + e

    solutions = [str(-b / (2 * a))]
    if a != 0 and d == 0:
        print "There's only one solution: " + solutions 

    solutions2 = [str((-b + math.sqrt(d)) / 2.0 / a), str((-b - math.sqrt(d)) / 2.0 / a)]
    if a != 0 and d > 0:
        print "There's two solutions: " + solutions2

    xre = str((-b) / (2 * a))
    xim = str((math.sqrt(-d)) / (2 * a))
    solutions3 = [xre + " + " + xim +"i", xre + " - " + xim +"i"]
    if a != 0 and d < 0:
        print "Solutions are: " + solutions3

我收到“ZeroDivisionError:浮点除以零”错误,因为当输入文件中的“b”为“0”时,我被零除。如何绕过错误,以便可以打印所需的文本?满足“if”条件时,我所需的输出必须是所需的打印语句。

其中(a,b,c)
    0.0, 0.0, 0.0

    0.0, 0.0, 1.0

    0.0, 2.0, 4.0

    1.0, 2.0, 1.0

    1.0, -5.0, 6.0

    1.0, 2.0, 3.0

最佳答案

我不懂Python。但是知道这个概念。

因此,请更正Python代码错误。

打印ax²+ bx + c = 0的解决方案

def roots4(outfile,a,b,c):
d = (b * b) - (4 * a * c)    


if a == 0 and b == 0 and c==0:
   print "This is not quadratic equations"
if a == 0 and b == 0:
   print "Invalid equations"
if a == 0:
   e = [str(-b / (2 * a))]
   print "There's only one solution: X=" + e        
if d == 0 :
   solutions = -b / (2 * a)
   print "Two roots are same X = " + solutions
if d > 0:
   solutions2 = [str((-b + math.sqrt(d)) / (2.0 * a)), str((-b - math.sqrt(d)) / (2.0 * a))]
   print "There's two solutions: " + solutions2
if d < 0:
   xre = str((-b) / (2 * a))
   xim = str((math.sqrt(-d)) / (2 * a))
   solutions3 = [xre + " + " + xim +"i", xre + " - " + xim +"i"]
   print "Solutions are: " + solutions3

关于python - 除以0时,我希望它打印给定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38781820/

相关文章:

javascript - 在 JavaScript 中使用超限序数

python - mysql数据库插入数据时出错

python - SQLAlchemy 查询过滤器行为在文档中令人困惑

如果使用的 Java 公式

失败函数的 C++ while 语句?

excel - 将包含超过 X 行数据的工作表复制到另一个工作簿

css - 选择正确的第 n 个 child

c++ - 高斯消元的逻辑错误

python - Pygame - 在某个特定时间渲染 Sprite

python - sin(x)/x 的数值积分