gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:26:55 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com