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
我得到了一个&#34; ZeroDivisionError:浮动除以零&#34;错误,因为我在&#34; b&#34;时除以零。是&#34; 0&#34;来自输入文件。如何绕过错误以便打印所需的文本?当满足&#34; if&#34;时,我想要的输出需要是所需的打印语句。条件。
其中(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
答案 0 :(得分:1)
您为什么要这样做?您能想到一种更好的文本显示方式吗?你根本不除以零怎么样?尝试显示结果而不用除以不除以零的方式除。
答案 1 :(得分: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