python
[Python] 纯文本查看 复制代码 import math
def quadratic(a, b, c):
if not isinstance(a, int) or not isinstance(b, int) or not isinstance(c, int):
raise TypeError('bad operand type')
if a == 0:
if b == 0:
if c == 0 :
result = ['无穷解']
else:
result = ['无解']
else:
#x1 = -c/b
x1 = '%d/%d' % (-c, b)
result = ['单实数解', x1]
elif b == 0 and c == 0:
result = ['单实数解', '0']
elif b**2-4*a*c > 0:
#x1 = (-b+math.sqrt(b**2-4*a*c))/2/a
#x2 = (-b-math.sqrt(b**2-4*a*c))/2/a
x1 = '(%d+sqrt(%d))/%d' % (-b, b**2-4*a*c, 2*a)
x2 = '(%d-sqrt(%d))/%d' % (-b, b**2-4*a*c, 2*a)
result = ['双实数解', x1, x2]
elif b**2-4*a*c == 0:
#x1 = -b/2/a
x1 = '%d/%d' % (-b, 2*a)
result = ['单实数解', x1]
else:
#x0 = math.sqrt(4*a*c-b**2)
#x1 = '(%d+%fi)/%d' % (-b, x0, 2*a)
#x2 = '(%d-%fi)/%d' % (-b, x0, 2*a)
x1 = '(%d+sqrt(%d)i)/%d' % (-b, 4*a*c-b**2, 2*a)
x2 = '(%d-sqrt(%d)i)/%d' % (-b, 4*a*c-b**2, 2*a)
result = ['双虚数解', x1, x2]
return result
a = int(input('输入整数a: '))
b = int(input('输入整数b: '))
c = int(input('输入整数c: '))
print('-----')
r = quadratic(a, b, c)
if len(r) == 1:
print(r[0])
elif len(r) == 2:
print('%s\nx = %s' % (r[0], r[1]))
else:
print('%s\nx1 = %s\nx2 = %s' % (r[0], r[1], r[2])) |