C Online Compiler
Example: Calculate Quadratic Equation Roots in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Calculate Quadratic Equation Roots #include <stdio.h> #include <math.h> // Required for sqrt() function int main() { // Step 1: Declare variables for coefficients and roots double a, b, c; double discriminant, root1, root2; double realPart, imagPart; int status_indicator; // Step 2: Get input from the user for coefficients printf("Enter coefficients a, b and c: "); scanf("%lf %lf %lf", &a, &b, &c); // Step 3: Check if 'a' is zero, as it's not a quadratic equation then if (a == 0) { printf("Error: 'a' cannot be zero for a quadratic equation.\n"); // For a=0, it becomes a linear equation bx + c = 0, x = -c/b if (b != 0) { printf("It's a linear equation. Root = %.2lf\n", -c / b); } else { printf("Invalid coefficients (a=0, b=0).\n"); } return 1; // Indicate an error } // Step 4: Calculate the discriminant discriminant = b * b - 4 * a * c; // Step 5: Determine the status based on discriminant value if (discriminant > 0) { status_indicator = 1; // Real and distinct roots } else if (discriminant == 0) { status_indicator = 0; // Real and equal roots } else { status_indicator = -1; // Complex roots } // Step 6: Use switch case to handle different root types switch (status_indicator) { case 1: // Case for real and distinct roots (discriminant > 0) root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); printf("Discriminant = %.2lf\n", discriminant); printf("Root 1 = %.2lf\n", root1); printf("Root 2 = %.2lf\n", root2); break; case 0: // Case for real and equal roots (discriminant == 0) root1 = -b / (2 * a); printf("Discriminant = %.2lf\n", discriminant); printf("Root 1 = Root 2 = %.2lf\n", root1); break; case -1: // Case for complex roots (discriminant < 0) realPart = -b / (2 * a); imagPart = sqrt(-discriminant) / (2 * a); printf("Discriminant = %.2lf\n", discriminant); printf("Root 1 = %.2lf + %.2lfi\n", realPart, imagPart); printf("Root 2 = %.2lf - %.2lfi\n", realPart, imagPart); break; } return 0; }
Output
Clear
ADVERTISEMENTS