How do you write a program in python that solves quadratic equations?

1 answer

Answer

1122717

2026-08-27 02:25

+ Follow

To write a program in Python that solves quadratic equations of the form ( ax^2 + bx + c = 0 ), you can use the quadratic formula ( x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} ). First, import the math module to use the sqrt function. Then, prompt the user for the coefficients ( a ), ( b ), and ( c ), calculate the discriminant ( D = b^2 - 4ac ), and use it to determine the roots. If ( D ) is positive, there are two real roots; if ( D ) is zero, there is one real root; and if ( D ) is negative, the roots are complex. Here's a simple implementation:

<code class="language-python">import math

def solve_quadratic(a, b, c): D = b**2 - 4<em>a</em>c if D > 0: root1 = (-b + math.sqrt(D)) / (2<em>a) root2 = (-b - math.sqrt(D)) / (2</em>a) return (root1, root2) elif D == 0: root = -b / (2<em>a) return (root,) else: realPart = -b / (2</em>a) imaginaryPart = math.sqrt(-D) / (2*a) return (complex(realPart, imaginaryPart), complex(realPart, -imaginaryPart))

<h1>Example usage</h1>

a, b, c = map(float, input("Enter coefficients a, b, c: ").split()) print(solve_quadratic(a, b, c)) </code>

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.