[Programming] Question 22: Write a program to Find all the roots of a quadratic equation in C

 

#include <stdio.h>
#include <math.h>

int main() {
	float a, b, c, discriminant, root1, root2, realPart, imaginaryPart;

	printf("Enter coefficients a, b, and c: ");
	scanf("%f %f %f", &a, &b, &c);

	discriminant = b * b - 4 * a * c;

	if (discriminant > 0) {
		root1 = (-b + sqrt(discriminant)) / (2 * a);
		root2 = (-b - sqrt(discriminant)) / (2 * a);
		printf("Roots are real and different.\n");
		printf("Root1 = %.2f\n", root1);
		printf("Root2 = %.2f\n", root2);
	}
	else if (discriminant == 0) {
		root1 = root2 = -b / (2 * a);
		printf("Roots are real and same.\n");
		printf("Root1 = Root2 = %.2f\n", root1);
	}
	else {
		realPart = -b / (2 * a);
		imaginaryPart = sqrt(-discriminant) / (2 * a);
		printf("Roots are complex and different.\n");
		printf("Root1 = %.2f + %.2fi\n", realPart, imaginaryPart);
		printf("Root2 = %.2f - %.2fi\n", realPart, imaginaryPart);
	}

	return 0;
} 

Inside the main() function:

- Float variables `a`, `b`, `c`, `discriminant`, `root1`, `root2`, `realPart`, and `imaginaryPart` are declared to store the coefficients of the quadratic equation, discriminant, roots, real part, and imaginary part respectively.

- The user is prompted to enter the coefficients of the quadratic equation.

- Discriminant is calculated using the formula b^2 - 4ac.

- Based on the value of discriminant, the nature of roots (real, equal, or complex) is determined and printed along with the roots.



Featured Posts

Leetcode 4. Median of Two Sorted Arrays

  4. Median of Two Sorted Arrays Hard Given two sorted arrays  nums1  and  nums2  of size  m  and  n  respectively, return  the median  of t...

Popular Posts