gpt4 book ai didi

python - 我除以零但没有提示 "ZeroDivisionError"

转载 作者:行者123 更新时间:2023-12-02 05:14:44 25 4
gpt4 key购买 nike

所以我使用二次方程来产生实根。root1 和 root2

当我除以零时,让A = 0

两个根分别是0.0-0.0

这应该给出错误:ZeroDivisionError

这是我的代码:

import math
A = float( input( "\nEnter the coefficient A: " ) )

B = float( input( "\nEnter the coefficient B: " ) )

C = float( input( "\nEnter the coefficient C: " ) )

print( "\nThe coefficients of the equation:\n" )
print( " Coefficient A = ", A )
print( " Coefficient B = ", B )
print( " Coefficient C = ", C )

root1 = -B + math.sqrt(B**2 - (4*A*C)) / 2*A
root2 = -B - math.sqrt(B**2 - (4*A*C)) / 2*A


print( "\nThe roots of the equation:\n" )
print( " Root #1 = ", round(root1,3) )
print( " Root #2 = ", round(root2,3) )

if A = 0 , B = 4.5, C = 8

输出为:

The roots of the equation:

Root #1 = -4.5
Root #2 = -4.5

最佳答案

Python就像数学,操作系统的顺序将使它除以2而不是乘以A,要改变它,像数学中那样做括号,也在您的所有操作 -B 丢失:

(-B + math.sqrt(B**2 - 4*A*C)) / (2 * A) 

或者除以两次:

(-B + math.sqrt(B**2 - 4*A*C)) / 2 / A  

关于python - 我除以零但没有提示 "ZeroDivisionError",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58945304/

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