C Online Compiler
Example: Solve Quadratic Equation Using Function in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Solve Quadratic Equation Using Function #include <stdio.h> #include <math.h> // Required for sqrt() function // Function to calculate and print roots of a quadratic equation void findRoots(double a, double b, double c) { double discriminant, root1, root2, realPart, imagPart; // Step 1: Calculate the discriminant discriminant = b * b - 4 * a * c; // Step 2: Check the value of the discriminant and calculate roots accordingly if (discriminant > 0) { // Case 1: Discriminant is positive (two distinct real roots) root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); printf("Roots are real and distinct.\n"); printf("Root 1 = %.2lf\n", root1); printf("Root 2 = %.2lf\n", root2); } else if (discriminant == 0) { // Case 2: Discriminant is zero (two identical real roots) root1 = root2 = -b / (2 * a); printf("Roots are real and identical.\n"); printf("Root 1 = Root 2 = %.2lf\n", root1); } else { // Case 3: Discriminant is negative (two complex conjugate roots) realPart = -b / (2 * a); imagPart = sqrt(-discriminant) / (2 * a); printf("Roots are complex and conjugate.\n"); printf("Root 1 = %.2lf + %.2lfi\n", realPart, imagPart); printf("Root 2 = %.2lf - %.2lfi\n", realPart, imagPart); } } int main() { double a, b, c; // Step 1: Get coefficients from the user printf("Enter coefficient a: "); scanf("%lf", &a); printf("Enter coefficient b: "); scanf("%lf", &b); printf("Enter coefficient c: "); scanf("%lf", &c); // Step 2: Handle the case where 'a' is zero (not a quadratic equation) if (a == 0) { printf("Coefficient 'a' cannot be zero for a quadratic equation.\n"); // If a=0, it's a linear equation: bx + c = 0 => x = -c/b if (b != 0) { printf("It's a linear equation. Root x = %.2lf\n", -c / b); } else if (c == 0) { printf("Infinite solutions (0 = 0).\n"); } else { printf("No solution (0 = -c, where c is non-zero).\n"); } } else { // Step 3: Call the function to find and print the roots findRoots(a, b, c); } return 0; }
Output
Clear
ADVERTISEMENTS