Python程序教程

您现在的位置是:首页 >  Python

当前栏目

Python求一元二次方程解「建议收藏」

Python,一元二次方程,建议,收藏
2025-04-07 09:01:28 时间

大家好,又见面了,我是你们的朋友全栈君。

题目: 请定义一个函数 ’quadratic(a,b,c)‘,接收三个参数,返回一元二次方程: ax² + bx + c = 0 的两个解。(提示:计算平方根可以调用math.sqrt()函数)

import math
def quadratic(a, b, c):
    if not isinstance(a, (int, float)):
        raise TypeError('a is not a number')
    if not isinstance(b, (int, float)):
        raise TypeErrot('b is not a number')
    if not isinstance(c, (int, float)):
        raise TypeError('c is not a number')
    derta = b * b - 4 * a * c
    if a == 0:
        if b == 0:
            if c == 0:
                return '方程根是全体实数'
            else:
               return '方程无根'
        else:
            x1 = -c / b
            x2 = x1
            return x1, x2
    else:
        if derta < 0:
            return '方程无根'
        else:
            x1 = (-b + math.sqrt(derta)) / (2 * a)
            x2 = (-b - math.sqrt(derta)) / (2 * a)
            return x1, x2
print(quadratic(2, 3, 1))
print(quadratic(1, 3, -4))

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/156154.html原文链接:https://javaforall.cn