求二次方程的解
Topic source修改了一版,这次考虑得比较全,只是验证a, b, c的合法性的方法还不是很好,当有两个以上的数不合法时每次只报错一个。
# -*- coding: utf-8 -*-
import math
a = float(input('please input a = '))
b = float(input('please input b = '))
c = float(input('please input c = '))
def quadratic(a, b, c):
if not isinstance (a, (int, float)):
raise TypeError ('error aaaaaa')
if not isinstance (b, (int, float)):
raise TypeError ('error bbbbbb')
if not isinstance (c, (int, float)):
raise TypeError ('error cccccc')
delta = b*b-4*a*c
if a == 0:
x1 = -c/b
return x1
elif (delta) > 0:
x1 = (-b + math.sqrt(delta)) / (2*a)
x2 = (-b - math.sqrt(delta)) / (2*a)
return x1, x2
elif (delta) == 0:
x1 = -b / (2*a)
return x1
else:
print ("无实数解")
print(quadratic(a, b, c))
a = float(input('please input a = '))在这一行代码中,如果输入了非数字,就会出Error了。要再设置三个参数,判断input的三个值是否是数字(可以用while判断多个)。如果都是数字,再赋值给a,b,c
- 1
yayayaxs