Discuss / Python / 求一元二次方程: ax^2 + bx + c = 0的两个解。

求一元二次方程: ax^2 + bx + c = 0的两个解。

Topic source

LeborYi

#1 Created at ... [Delete] [Delete and Lock User]
import math

def quadratic(a,b,c):
    x = b * b - 4 * a * c 
    if x < 0:
        print('此方程无解')
    elif x == 0:
        y = -b /(2 * a)
        print('此方程有唯一解:',y)
    else:
        y1 = (-b + math.sqrt(x))/(2 * a)
        y2 = (-b - math.sqrt(x))/(2 * a)
        print('此方程有两个不同解:',y1,y2)
    return

quadratic(2,3,1)

quadratic(1,3,-4)
input()

1.返回值的时候空格和Tab不能混用,否则会报错; 2.x==0才是判断语句,而不是x=0.这是赋值语句。

SaraMolly

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

import math def quadratic(a,b,c): y=bb/(4aa)-c/a if y<0: print('无解') elif y==0: x=-b/(2a) print('唯一解:',x) else: x1=math.sqrt(-c/a+bb/(4aa))-b/(2a) x2=-math.sqrt(-c/a+bb/(4aa))-b/(2a) print('有两个不同解:',x1,x2) return

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


  • 1

Reply