Discuss / Python / 练习题

练习题

Topic source

Gussun

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

①等于号是,== ②检测参数合法性,需要一个个检测,并注意标注错误的发生地

# -*- coding:utf-8 -*-
import math

print('你好,这是一个求一元二次方程的计算器。')

#定义函数体
def quadratic(a,b,c):
    if not isinstance(a,(int,float)):
        raise TypeError('bad operand type a')
    if not isinstance(b,(int,float)):
        raise TypeError('bad operand type b')
    if not isinstance(c,(int,float)):
        raise TypeError('bad operand type c')

    delt=b*b-4*a*c
    if a==0:
        x=(-c)/b
        return "这是一个一元一次方程,方程具有唯一解,'x=%.2f'" %(x)
    elif delt<0:
        return '该二次方程无解'
    elif delt==0:
        x=(-b)/2*a
        return '该方程有唯一解%.2f' %(x)
    else:
        x1=(-b+math.sqrt(delt))/2*a
        x2=(-b-math.sqrt(delt))/2*a
        return "该方程有两个解,'x1'=%.2f ,'x2'=%.2f" %(x1,x2)

#请求数据
a=float(input('请输入二次项系数:'))
b=float(input('请输入一次项系数:'))
c=float(input('请输入常数项系数:'))

#输出结果

print(quadratic(a,b,c))

囧灰黄

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

/2乘以a 应该改为/(2乘以a)

Delta-C

#3 Created at ... [Delete] [Delete and Lock User]
if not isinstance(a,(int,float)):
        raise TypeError('bad operand type a')
    if not isinstance(b,(int,float)):
        raise TypeError('bad operand type b')
    if not isinstance(c,(int,float)):
        raise TypeError('bad operand type c')

请问,这些有什么用那? a = float(input('please input a = '))在这一行代码中,如果输入了非数字,就会出Error了。 输入后一定是float,判断没什么用啊


  • 1

Reply