Roots of a Quadratic equation in C


SUBMITTED BY: kaushal1981

DATE: Feb. 21, 2017, 9:18 p.m.

FORMAT: Text only

SIZE: 990 Bytes

HITS: 826

  1. #include <stdio.h>
  2. #include <math.h>
  3. int main()
  4. {
  5. double a, b, c, determinant, root1,root2, realPart, imaginaryPart;
  6. printf("Enter coefficients a, b and c: ");
  7. scanf("%lf %lf %lf",&a, &b, &c);
  8. determinant = b*b-4*a*c;
  9. // condition for real and different roots
  10. if (determinant > 0)
  11. {
  12. // sqrt() function returns square root
  13. root1 = (-b+sqrt(determinant))/(2*a);
  14. root2 = (-b-sqrt(determinant))/(2*a);
  15. printf("root1 = %.2lf and root2 = %.2lf",root1 , root2);
  16. }
  17. //condition for real and equal roots
  18. else if (determinant == 0)
  19. {
  20. root1 = root2 = -b/(2*a);
  21. printf("root1 = root2 = %.2lf;", root1);
  22. }
  23. // if roots are not real
  24. else
  25. {
  26. realPart = -b/(2*a);
  27. imaginaryPart = sqrt(-determinant)/(2*a);
  28. printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart, imaginaryPart);
  29. }
  30. return 0;
  31. }

comments powered by Disqus