
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)
Editorial
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. |
Solution Hints
- Compute the discriminant D = b² - 4ac.
- Handle cases based on D > 0, D = 0, or D < 0.