Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <math.h>
- void quadraticSolver(int a, int b, int c) // A, B, and C are in ax^2 + bx + c = 0 quadratic
- {
- 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)
- if (ppcsr < 0)
- {
- 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 ;-;
- return; // P.S. This also prevents a negative value being sent to the sqrt() function
- }
- if (ppcsr == 0) // If there will only be 1 solution...
- {
- double bd = b;
- double x = -bd / (2 * a); // Use the Quadratic Formula to calculate for the only X intercept
- printf("x = %f", x);
- return;
- }
- 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.
- else // If the code reaches this point, there will be 2 real solutions.
- {
- double x1 = (-b + pcsr) / (2 * a); // Use quadratic formula to solve for the first X-int.
- double x2 = (-b - pcsr) / (2 * a); // Use quadratic formula to solve for the second X-int.
- printf("x = %f, %f", x1, x2);
- return;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement