Advertisement
Kyojin96

Quadratic equation calculator

Nov 9th, 2015
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.91 KB | None | 0 0
  1. /*
  2.     Discriminant calculator in C
  3.     Author: Kyojin96
  4.     Date: 9.11.2015
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <math.h>
  10.  
  11. int main()
  12. {
  13.     /* Variables */
  14.     int a, b, c;
  15.     float x1, x2, D, re, im;
  16.  
  17.  
  18.     /* We need input for a, b & c */
  19.     printf("a = "); scanf("%d", &a);
  20.     printf("b = "); scanf("%d", &b);
  21.     printf("c = "); scanf("%d", &c);
  22.  
  23.     /* if both equal 0 then it's degenerated */
  24.     if(a == 0 && b == 0)
  25.     {
  26.         printf("The equation is degenerated\n");
  27.     }
  28.     /* in this case x = -c/b */
  29.     else if(a == 0 && b != 0)
  30.     {
  31.         x1 = -c/b;
  32.         printf("The equation has only one root x1 = %f\n", x1);
  33.     }
  34.     /* Check c first for optimisation */
  35.     else if(c == 0 && a != 0 && b != 0)
  36.     {
  37.         x1 = -b/a;
  38.         x2 = 0;
  39.         printf("The equation has two roots x1 = %f and x2 = %f\n", x1, x2);
  40.     }
  41.     /* if all are bigger than 0 then calculate discriminant */
  42.     else if(a != 0 && b != 0 && c != 0)
  43.     {
  44.         /* Use math funcs to power b a.k.a b^2 */
  45.         float bPowered = pow(b, 2);
  46.         D = bPowered - 4 * a * c;
  47.  
  48.         /* If discriminant is more than 0, it has 2 roots */
  49.         if(D > 0)
  50.         {
  51.             x1 = (-b + sqrt(D))/(2 * a);
  52.             x2 = (-b - sqrt(D))/(2 * a);
  53.             printf("The equation has 2 roots x1 = %f and x2 = %f\n", x1, x2);
  54.         }
  55.         /* If it's less than 0, it has real and imaginary numbers */
  56.         else if(D < 0)
  57.         {
  58.             re = -b/2*a;
  59.             im = sqrt(fabs(D))/2*a;
  60.             printf("The equation has real part re = %f and imaginery im = %f\n", re, im);
  61.         }
  62.         /* Else if it's 0 then it has two equal roots */
  63.         else
  64.         {
  65.             x1 = -b/2*a;
  66.             printf("The equation has two equal roots x1 = x2 = %f\n", x1);
  67.         }
  68.     }
  69.  
  70.     /* Pause the console app */
  71.     system("pause");
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement