介紹三種方法如下
1、
#!/usr/bin/env python# coding=utf-8""" solving a quadratic equation"""from __future__ import divisionimport mathdef quadratic_equation(a,b,c): delta=b*b-4*a*c if delta<0: return False elif delta ==0: return -(b/(2*a)) else: sqrt_delta=math.sqrt(delta) x1=(-b+ sqrt_delta)/(2*a) x2=(-b- sqrt_delta)/(2*a) return x1,x2if __name__=="__main__": PRint "a quadratic equation: x^2 +x+1=0" coefficients=(1,1,1) roots=quadratic_equation(*coefficients) if roots: print "the result is:", roots else: print "this equation has no solution."2、#!/usr/bin/env python# coding=utf-8from __future__ import division # 除法糾正import mathdef oneandtwo(): """判斷方程的根;若方程有根,則將其解出來""" delta = b ** 2 - 4 * a * c # 根的判別式 print "判別式大小為:", delta print if delta < 0: print "根的判別式小于0,方程無解!" else: x1 = (-b + math.sqrt(delta)) / (2 * a) # 第一個根 x2 = (-b - math.sqrt(delta)) / (2 * a) # 第二個根 print "方程的兩根是:/n/nx1=%f/nx2=%f" % (x1, x2) printif __name__ == "__main__": print "輸入一元二次方程的系數(a,b,c):" print stra = raw_input("請輸入系數 a:") strb = raw_input("請輸入系數 b:") strc = raw_input("請輸入系數 c:") print print "方程是:(%s)*x^2+(%s)*x+(%s)=0" % (stra, strb, strc) print # 將輸入的字符串轉換為浮點數 a = float(stra) b = float(strb) c = float(strc) oneandtwo() # 調用并打印出方程的兩個根 3、#!/usr/bin/env python# coding=utf-8import mathdef quadratic_equation(a, b, c): t = math.sqrt(pow(b, 2) - 4 * a * c) if(pow(b, 2) - 4 * a * c) > 0: return (-b + t) / (2 * a), (-b - t) / (2 * a) elif (pow(b, 2) - 4 * a * c) == 0: return (-b + t) / (2 * a) else: return Noneprint quadratic_equation(2, 3, 0)print quadratic_equation(1, -6, 5)
新聞熱點
疑難解答