為什么計(jì)算結(jié)果和答案不同?
import math
def quadratic_equation(a, b, c):
? ? x1=(-b+math.sqrt(b**2-4.0*a*c))/2.0*a
? ? x2=(-b-math.sqrt(b**2-4.0*a*c))/2.0*a
? ? return x1,x2
print quadratic_equation(2, 3, 0)
print quadratic_equation(1, -6, 5)
代碼可以運(yùn)行,但是答案提示錯(cuò)誤
2020-02-27
因?yàn)槟?2.0*a沒有用括號(hào)括起來
實(shí)際上運(yùn)行的是先/2.0再*a
x1=(-b+math.sqrt(b**2-4.0*a*c))/(2.0*a)
x2=(-b-math.sqrt(b**2-4.0*a*c))/(2.0*a)
就可以了
2020-02-27
不需要用2.0和4.0 你可以測(cè)下 sqrt函數(shù)運(yùn)算完就是浮點(diǎn)型?
print math.sqrt(3**2-4*2*0)
結(jié)果是3.0