Pythonは二次方程式の根を見つけます

次の例は、ユーザーが数値を入力し、2次方程式を計算することです。

# 导入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)

2番目の方法:

# 计算二次方根的解
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)

おすすめ

転載: blog.csdn.net/Progresssing/article/details/108845115