Tutorialspoint
Problem
Solution
Submissions

Roots of a Quadratic Equation

Certification: Basic Level Accuracy: 66.67% Submissions: 3 Points: 10

Write a C++ program to find the roots of a quadratic equation ax² + bx + c = 0. Handle real and complex roots.

Example 1
  • Input: a = 1, b = -3, c = 2
  • Output: "Real and distinct roots: 2.000 and 1.000"
  • Explanation:
    • Step 1: Calculate the discriminant (b² - 4ac) = (-3)² - 4×1×2 = 9 - 8 = 1.
    • Step 2: Since discriminant > 0, there are two real roots.
    • Step 3: Calculate roots using the quadratic formula: x = (-b ± √(b² - 4ac))/2a.
    • Step 4: x₁ = (-(-3) + √1)/2×1 = 2.000, x₂ = (-(-3) - √1)/2×1 = 1.000.
Example 2
  • Input: a = 1, b = 0, c = 1
  • Output: "Complex roots: 0.000+1.000i and 0.000-1.000i"
  • Explanation:
    • Step 1: Calculate the discriminant (b² - 4ac) = 0² - 4×1×1 = 0 - 4 = -4.
    • Step 2: Since discriminant < 0, there are two complex roots.
    • Step 3: Calculate real part: -b/2a = 0/2 = 0.000.
    • Step 4: Calculate imaginary part: √|discriminant|/2a = √4/2 = 1.000.
    • Step 5: Express roots in the form: real±imaginary·i.
Constraints
  • a, b, c are real numbers and a ≠ 0
  • Output should format real numbers with 3 decimal places
  • Time Complexity: O(1)
  • Space Complexity: O(1)
NumberTutorialspointWalmart
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Compute the discriminant D = b² - 4ac.
  • Handle cases based on D > 0, D = 0, or D < 0.

Steps to solve by this approach:

 Step 1: Calculate the discriminant (b²-4ac).

 Step 2: Check if the discriminant is greater than 0 (two real roots).
 Step 3: If positive, calculate both roots using the quadratic formula.
 Step 4: If the discriminant equals 0, calculate the single repeated root.
 Step 5: If the discriminant is negative, calculate the real and imaginary parts of the complex roots.
 Step 6: Display the roots with appropriate messages based on their type.

Submitted Code :