Discuss / Python / 作业

作业

Topic source

import math

def quadratic(a, b, c):

    if not isinstance(a, (int, float)) and isinstance(b, (int, float)) and isinstance(int, float):

        raise TypeError('数据类型错误,请输入整数or小数')

    g=math.sqrt(b ** 2 - 4 * a * c)

    if g < 0 or a == 0:

        print('无实数解')

    else:

        x1 = (-b * g) / (2 * a)

        x2 = (-b * -g) / (2 * a)

        if x1 == x2:

            return x1

        else:

            return x1, x2

print(quadratic(2, 3, 1))

print(quadratic(1, 3, -4))

吃了读书少的亏。-b±√(b^2-4ac)应该理解成-b乘以±根号,而不是-b加减根号吧。因为b是字母省略了运算符号。看评论区都是加减。我也写了加减。答案不对。懵了半天

Post

#3 Created at ... [Delete] [Delete and Lock User]

你这是(-b*delta)/2a了吧,公式不对呀。

余昧

#4 Created at ... [Delete] [Delete and Lock User]

大哥,人家都给了一元二次方程的求解公示了,还能理解错误。。。。。

余昧

#5 Created at ... [Delete] [Delete and Lock User]

就比如,a±b,你怎么能理解成 a ✖ (±b) 呢?

余昧

#6 Created at ... [Delete] [Delete and Lock User]

并且判断三个参数类型那段 if 语句也有问题,我是这样写的:

if not (isinstance(a, int or float) and isinstance(b, int | float) & isinstance(c, int | float)):

   raise TypeError("输入参数a,b,c 不符合规则。")

余昧

#7 Created at ... [Delete] [Delete and Lock User]

哦,网页运行好像不支持 '|' 的 ’或‘,只能用 'or' 

if not (isinstance(a, int or float) & isinstance(b, int or float) & isinstance(c, int or float)):

余昧

#8 Created at ... [Delete] [Delete and Lock User]

发现自己写错了 isinstance 函数的用法。又改了一遍:

    if not (isinstance(a, (int, float)) and isinstance(b, (int, float)) and isinstance(c, (int, float))):


  • 1

Reply