Print Real or Complex Solutions
In this step, you'll enhance the quadratic equation solver to provide more detailed output and handle different solution types with improved formatting.
Open the existing file and update the code:
cd ~/project
nano quadratic_solver.c
Replace the previous code with the following:
#include <stdio.h>
#include <math.h>
void printQuadraticSolutions(double a, double b, double c) {
double discriminant = b * b - 4 * a * c;
printf("Quadratic Equation: %.2fx² + %.2fx + %.2f = 0\n", a, b, c);
printf("Discriminant: %.2f\n", discriminant);
if (discriminant > 0) {
double root1 = (-b + sqrt(discriminant)) / (2 * a);
double root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Solution Type: Two Distinct Real Roots\n");
printf("Root 1: %.2f\n", root1);
printf("Root 2: %.2f\n", root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
printf("Solution Type: One Real Root (Repeated)\n");
printf("Root: %.2f\n", root);
} else {
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Solution Type: Complex Conjugate Roots\n");
printf("Root 1: %.2f + %.2fi\n", realPart, imaginaryPart);
printf("Root 2: %.2f - %.2fi\n", realPart, imaginaryPart);
}
}
int main() {
double a, b, c;
printf("Quadratic Equation Solver\n");
printf("------------------------\n");
printf("Enter coefficient a: ");
scanf("%lf", &a);
printf("Enter coefficient b: ");
scanf("%lf", &b);
printf("Enter coefficient c: ");
scanf("%lf", &c);
printf("\n");
printQuadraticSolutions(a, b, c);
return 0;
}
Compile the program:
gcc quadratic_solver.c -o quadratic_solver -lm
Run the program with different scenarios:
./quadratic_solver
Example output (two real roots):
Quadratic Equation Solver
------------------------
Enter coefficient a: 1
Enter coefficient b: -5
Enter coefficient c: 6
Quadratic Equation: 1.00x² + -5.00x + 6.00 = 0
Discriminant: 1.00
Solution Type: Two Distinct Real Roots
Root 1: 3.00
Root 2: 2.00
Example output (one real root):
Quadratic Equation Solver
------------------------
Enter coefficient a: 1
Enter coefficient b: -2
Enter coefficient c: 1
Quadratic Equation: 1.00x² + -2.00x + 1.00 = 0
Discriminant: 0.00
Solution Type: One Real Root (Repeated)
Root: 1.00
Example output (complex roots):
Quadratic Equation Solver
------------------------
Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 5
Quadratic Equation: 1.00x² + 2.00x + 5.00 = 0
Discriminant: -16.00
Solution Type: Complex Conjugate Roots
Root 1: -1.00 + 2.00i
Root 2: -1.00 - 2.00i
Key improvements:
- Created a separate function
printQuadraticSolutions()
for better code organization
- Added more descriptive output with solution type and equation details
- Maintained the same root calculation logic from previous step
- Improved user interface with a title and clear formatting