以下实例为通过用户输入数字,并计算二次方程:
# 导入cmath(复杂运算)模块
import cmath
# 计算二次方程根的解
def result(a,b,c):
sol1 = (-b + cmath.sqrt(b ** 2 - 4 * a * c)) / 2 * a
sol2 = (-b - cmath.sqrt(b ** 2 - 4 * a * c)) / 2 * a
print('结果为{0}和{1}'.format(sol1,sol2))
# 输入二次方程系数
a=float(input('输入a:'))
b=float(input('输入b:'))
c=float(input('输入c:'))
# 判断是否是二次函数
if a==0:
print('不是二次方程,请重新输入!')
a=float(input('输入a:'))
result(a,b,c)
else:
result(a,b,c)
第二种方式:
# 计算二次方根的解
def result(a,b,c):
sol1 = (-b + (b ** 2 - 4 * a * c)**(1/2)) /2 * a
sol2 = (-b - (b ** 2 - 4 * a * c))**(1/2) / 2 * a
print('结果为{:.2f}和{:.2f}'.format(sol1,sol2))
# 输入二次方程系数
a=float(input('输入a:'))
b=float(input('输入b:'))
c=float(input('输入c:'))
# 判断是否是二次函数
if a==0:
print('不是二次方程,请重新输入!')
a=float(input('输入a:'))
result(a,b,c)
else:
result(a,b,c)