請定義一個函數quadratic(a, b, c),接收3個參數,返回一元二次方程 ax^2+bx+c=0的兩個解。
提示:
一元二次方程的求根公式為:
x1 = (-b + math.sqrt((b * b) - (4 * a * c))) / (2 * a)
x2 = (-b - math.sqrt((b * b) - (4 * a * c))) / (2 * a)
計算平方根可以調用math.sqrt()函數
# -*- coding: utf-8 -*-
# 請定義一個函數quadratic(a, b, c),接收3個參數,返回一元二次方程 ax^2+bx+c=0的兩個解
import math
def quadratic(a,b,c):
x1 = (-b + math.sqrt((b * b) - (4 * a * c))) / (2 * a)
x2 = (-b - math.sqrt((b * b) - (4 * a * c))) / (2 * a)
return x1,x2
print('quadratic(2,3,1) = ' , quadratic(2,3,1))
print('quadratic(1,3,-4) = ' , quadratic(1,3,-4))
if quadratic(2,3,1) != (-0.5, -1.0):
print('測試失敗')
elif quadratic(1,3,-4) != (1.0, -4.0):
print('測試失敗')
else:
print('測試成功')
