Advertisement
2insanepeople

Quadratic equation solver function

May 28th, 2015
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. void quadraticSolver(int a, int b, int c) // A, B, and C are in ax^2 + bx + c = 0 quadratic
  5. {
  6.     int ppcsr = b*b - (4*a*c); // Allows for checking if there will be no solutions VERY quickly. Stands for pre-pre-calculated square root (AKA discriminant)
  7.     if (ppcsr < 0)
  8.     {
  9.         printf("No solutions"); // I would normally return a double[] for this setup, but this catch kept me from doing so because I can't throw exceptions in C ;-;
  10.         return; // P.S. This also prevents a negative value being sent to the sqrt() function
  11.     }
  12.     if (ppcsr == 0) // If there will only be 1 solution...
  13.     {
  14.         double bd = b;
  15.         double x = -bd / (2 * a); // Use the Quadratic Formula to calculate for the only X intercept
  16.         printf("x = %f", x);
  17.         return;
  18.     }
  19.         double pcsr = sqrt(ppcsr); // Pre-calculates square root. This allows for faster catching of single solution cases, and makes you only have to calculate this value once rather than twice.
  20.     else // If the code reaches this point, there will be 2 real solutions.
  21.     {
  22.         double x1 = (-b + pcsr) / (2 * a); // Use quadratic formula to solve for the first X-int.
  23.         double x2 = (-b - pcsr) / (2 * a); // Use quadratic formula to solve for the second X-int.
  24.         printf("x = %f, %f", x1, x2);
  25.         return;
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement