Python小程序-写一个计算一元二次方程的程序函数

题目要求:

请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:ax^2 + bx + c = 0的两个解。

程序代码:

这只是一个函数,如果你不调用它的话,是不会产生任何输出的。

import math
def quadratic(a, b, c):
    if not (isinstance(a,(int,float)) and isinstance(b,(int,float)) and isinstance(c,(int,float))):
        return '请输入数字'
    else:
        d = -c + (b/2) ** 2
    if d < 0:
        return '无解'
    else:
        x1 = round((math.sqrt(d) - (b/2)) / a , 2)
        x2 = round((-math.sqrt(d) - (b/2)) / a , 2)
        return x1,x2

小结:

求数字的平方根可以使用math.sqrt()函数,需引入math模块。

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha Code