„Python“ programa kvadratinei lygčiai išspręsti

Ši programa apskaičiuoja kvadratinės lygties šaknis, kai žinomi koeficientai a, b ir c.

Norėdami suprasti šį pavyzdį, turite žinoti apie šias „Python“ programavimo temas:

  • „Python“ duomenų tipai
  • „Python“ įvestis, išvestis ir importas
  • „Python“ operatoriai

Standartinė kvadratinės lygties forma yra:

ax 2 + bx + c = 0, kur a, b ir c yra realieji skaičiai ir a ≠ 0

Pirminis kodas

# Solve the quadratic equation ax**2 + bx + c = 0 # import complex math module import cmath a = 1 b = 5 c = 6 # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are (0) and (1)'.format(sol1,sol2)) 

Rezultatas

 Įveskite a: 1 Įveskite b: 5 Įveskite c: 6 Sprendimai yra (-3 + 0j) ir (-2 + 0j)

Mes importavome cmathmodulį, kad atliktume sudėtingą kvadratinę šaknį. Pirmiausia apskaičiuojame diskriminantą ir tada randame du kvadratinės lygties sprendimus.

Pirmiau pateiktoje programoje galite pakeisti a, b ir c vertes ir išbandyti šią programą.

Įdomios straipsniai...