Discuss / Python / 交作业

交作业

Topic source

-- coding: utf-8 --

import math

def quadratic(a, b, c): if not isinstance(a, (int, float)): raise TypeError('bad operand type') if not isinstance(b, (int, float)): raise TypeError('bad operand type') if not isinstance(c, (int, float)): raise TypeError('bad operand type') if a == 0: return -1 c / b else: return (-b + math.sqrt(b**2-4ac)) / (2a), (-b - math.sqrt(b*2-4ac)) / (2a)

-- coding: utf-8 --

import math

def quadratic(a, b, c): if not isinstance(a, (int, float)): raise TypeError('bad operand type') if not isinstance(b, (int, float)): raise TypeError('bad operand type') if not isinstance(c, (int, float)): raise TypeError('bad operand type') if a == 0: return - c / b else: return (-b + math.sqrt(b2-4ac)) / (2*a), (-b - math.sqrt(b2-4ac)) / (2*a)

-- coding: utf-8 --

import math

def quadratic(a, b, c): if not isinstance(a, (int, float)): raise TypeError('bad operand type') if not isinstance(b, (int, float)): raise TypeError('bad operand type') if not isinstance(c, (int, float)): raise TypeError('bad operand type') if a == 0: return - c / b else: return (-b + math.sqrt(b2-4ac)) / (2*a), (-b - math.sqrt(b2-4ac)) / (2*a)

#还要a、考虑开平方根时不能为负数,b、除了a==0要考虑还有b==0的情况也要考虑

skychi

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

import math

def quadratic(a, b, c): if not isinstance(a, (int, float)): raise TypeError('bad operand type') if not isinstance(b, (int, float)): raise TypeError('bad operand type') if not isinstance(c, (int, float)): raise TypeError('bad operand type')

if a == 0:
    if b != 0:
        x = -c / b
        return '此方程有一解: %s' % x
    elif c == 0:
        return '此方程有任意解'
    else:
        return '此方程无解'

# delta = pow(b, 2) - 4 * a * c
delta = b ** 2 - 4 * a * c
if delta < 0:
    return '此方程无解'
elif delta == 0:
    x = -b / (2 * a)
    return '此方程有一解: %s' % x
else:
    x1 = (-b + math.sqrt(delta))/(2 * a)
    x2 = (-b - math.sqrt(delta))/(2 * a)
    return '此方程解为:(%s,%s)' % (x1, x2)

print('quadratic(0, 1, 0)', quadratic(0, 1, 0))

print('quadratic(0, 0, 0)', quadratic(0, 0, 0))

print('quadratic(0, 0, 1)', quadratic(0, 0, 1))

print('quadratic(4, 2, 1)', quadratic(4, 2, 1))

print('quadratic(1, 2, 1)', quadratic(1, 2, 1))

print('quadratic(2, 3, 1)', quadratic(2, 3, 1))

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


  • 1

Reply