关于python:当除以0时,我希望它打印给定的文本

When didving by 0, I want it to print given text

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import math

def roots4(outfile,a,b,c):
   """Prints the solutions of 'x' for equation ax2 + 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:float division by zero"错误,因为当输入文件中"b"为"0"时,我除以零。 如何绕过错误以便打印所需的文本? 满足"if"条件时,我想要的输出需要是所需的打印语句。

其中(a,b,c)

1
2
3
4
5
6
7
8
9
10
11
    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代码错误。

打印ax2 + bx + c = 0的解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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