Discuss / Python / 作业

作业

Topic source

Geek_MrHowe

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-
import math
def quadratic(a, b, c):
    if not isinstance(a,(int,float)) and instance(b,(int,float)) and (c,(int,float)):
        raise TypeError('bad operand type')
    else:
        m=math.sqrt(b*b-4*a*c)
        return (-b+m)/(2*a),(-b-m)/(2*a)
print("请输入一元二次方程a,b,c的值")
a=input('a:')
b=input('b:')
c=input('c:')
print("一元二次方程的解为%f,%f"%quadratic(float(a), float(b), float(c)))

结果

请输入一元二次方程a,b,c的值
a:5
b:33
c:2
一元二次方程的解为-0.061173,-6.538827

休电脑的

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

答案中: a=input('a:') b=input('b:') c=input('c:') 输入的结果,给a,b,c,赋的值应该是字符串吧,那么赋值以后,再进入函数中判断数据类型,应该都是错的吧,既不是int也不是float,为什么还能执行下去呢?

休电脑的

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

终于找到原因了,

print("一元二次方程的解为%f,%f"%quadratic(float(a), float(b), float(c)))

在这一句中,把abc的输入赋值从字符串变为float了,所以可以执行下去。

但是,你这个程序,如果abc输入字母的话,是会直接报错,而不是

raise TypeError('bad operand type')

而且,貌似实际上没办法用判断的方式,在输入非法数据的时候报这个bad operand type。 这个问题纠结我一晚上了。


  • 1

Reply