Discuss / Python / 本节练习

本节练习

Topic source

心灵旅者

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-
import math
def quadratic(a, b, c):
    if not isinstance(a,(int,float)):
       raise TypeError('operand a: bad operand type.')
    if not isinstance(b,(int,float)):
       raise TypeError('operand b: bad operand type.')
    if not isinstance(c,(int,float)):
       raise TypeError('operand c: bad operand type.')
    d=b*b-4*a*c
    if a==0:
        r1=-b/c
        return r1
    elif d>=0:
        r1=(-b+math.sqrt(d))/(2*a)
        r2=(-b-math.sqrt(d))/(2*a)
        return r1,r2
    else:
        print('无实数解.')

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

艳艳IT

#2 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-
import math
a=input('please input a=')
b=input('please input b=')
c=input('please input c=')
a=int(a)
b=int(b)
c=int(c)
print('the equation you input is %dx^2 + %dx + %d' %(a,b,c))
def equation(a,b,c):
    if(b*b-4*a*c<0):
        print('the equation does not have solutions')
        exit()
    else:
        x1=round((-b+math.sqrt(b*b-4*a*c))/(2*a),2)
        x2=round((-b-math.sqrt(b*b-4*a*c))/(2*a),2)
        print('the solutions of the equation is x1=%.2f, x2=%.2f' %(x1,x2))
        return x1,x2
x1,x2=equation(a,b,c)

  • 1

Reply