繁体   English   中英

我除以零但没有提示“ZeroDivisionError”

[英]I am dividing by zero but no “ZeroDivisionError” is prompted

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

当我除以零时,让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

output 是:

The roots of the equation:

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

/*的优先级相同。 所以以下将与A相乘,而不是除以它:

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

此外,您只划分sqrt部分,不包括-B 将其更改为

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

或者

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

Pythons 就像数学一样,操作系统的顺序将使其除以2而不是与A相乘,要更改它,请像数学一样做括号,在所有操作中-B也缺失:

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

或分两次:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM