Monday, 28 October 2013

[C Programming] Find roots of any quadratic equation

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

void main()
{
  int coefficient_a, coefficient_b, coefficient_c;
  int delta;
  float root1, root2;
  float temp;
 
  printf("Enter values for coefficients a, b and c\n");
  scanf("%d%d%d", &coefficient_a, &coefficient_b, &coefficient_c);
 
  printf("Entered expression is\n");
  printf("%dx^2 + %dx + %d\n", coefficient_a, coefficient_b, coefficient_c);
 
  if (!coefficient_a) {
  printf("Entered equation is not a quadratic equation, since coefficient_a is ZERO\n");
  return;
     }

  delta = (coefficient_b * coefficient_b) - (4 * coefficient_a * coefficient_c);
 
  if (delta > 0){
  /* Roots are Real numbers */
  printf("Roots are Real numbers\n");
  root1 = (-coefficient_b + sqrt(delta)) / (2 * coefficient_a);
  root2 = (-coefficient_b - sqrt(delta)) / (2 * coefficient_a);
 
  printf(" Roots are %f and %f\n", root1, root2);
  }
  else {
 /* Roots are imaginary numbers
  * roots = (-b +- i sqrt(4*a*c-b*b)) / (2*a)
  * temp = -b/2*a;
  * root1 = temp + i sqrt(4*a*c-b*b)/(2*a);
  * root2 = temp - i sqrt(4*a*c-b*b)/(2*a);
  */
 printf("Roots are imaginary numbers\n");
 temp = -coefficient_b / (2 * coefficient_a);
 root1 = sqrt(-delta) / (2 * coefficient_a);
   root2 = -sqrt(-delta) / (2 * coefficient_a);
   printf(" Roots are %f + i(%f) and %f + i(%f)\n", temp, root1, temp, root2);
  }
}

Output1:
---------
Enter values for coefficients a, b and c
1
5
6
Entered expression is
1x^2 + 5x + 6
Roots are Real numbers
 Roots are -2.000000 and -3.000000


Output2:
-----------
Enter values for coefficients a, b and c
1
2
8
Entered expression is
1x^2 + 2x + 8
Roots are imaginary numbers
 Roots are -1.000000 + i(2.645751) and -1.000000 + i(-2.645751)

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...