C Online Compiler
Example: Find Roots of Quadratic Equation in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Roots of Quadratic Equation #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, realPart, imagPart; // Step 2: Prompt user for coefficients printf("Enter coefficient a: "); scanf("%lf", &a); printf("Enter coefficient b: "); scanf("%lf", &b); printf("Enter coefficient c: "); scanf("%lf", &c); // Step 3: Check if 'a' is zero if (a == 0) { printf("Error: Coefficient 'a' cannot be zero for a quadratic equation.\n"); printf("This is a linear equation: %.2lfX + %.2lf = 0\n", b, c); // For a linear equation, if b is also 0, it's either no solution or infinite solutions. // Otherwise, x = -c/b if (b != 0) { printf("Root for linear equation: X = %.2lf\n", -c/b); } else { if (c == 0) { printf("Infinite solutions (0 = 0).\n"); } else { printf("No solution (e.g., 5 = 0).\n"); } } return 1; // Exit with an error code } // Step 4: Calculate the discriminant discriminant = b * b - 4 * a * c; // Step 5: Determine roots based on the discriminant's value if (discriminant > 0) { root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); printf("Two distinct real roots: X1 = %.2lf and X2 = %.2lf\n", root1, root2); } else if (discriminant == 0) { root1 = root2 = -b / (2 * a); // Both roots are equal printf("One real root (or two equal real roots): X = %.2lf\n", root1); } else { // discriminant < 0 realPart = -b / (2 * a); imagPart = sqrt(-discriminant) / (2 * a); // Use -discriminant because discriminant is negative printf("Two complex conjugate roots: X1 = %.2lf+%.2lfi and X2 = %.2lf-%.2lfi\n", realPart, imagPart, realPart, imagPart); } return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS