-
-
Save tuankiet65/2d55c0bcda66ffa78f65bca425345356 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <math.h> | |
#include <stdio.h> | |
#define INF 0x6996 | |
/* solve_quadratic(): solve the quadratic equation */ | |
/* returns the number of valid roots */ | |
/* resulting roots are stored in roots[2] */ | |
int solve_quadratic(double a, double b, double c, double roots[2]) { | |
double delta; | |
/* special case: a == b == c == 0 => infinite roots */ | |
if (a == 0 && b == 0 && c == 0) return INF; | |
/* special case: a == b == 0; c != 0 => no roots */ | |
if (a == 0 && b == 0 && c != 0) return 0; | |
delta = pow(b, 2) - (4 * a * c); | |
printf("delta is %.6lf\n", delta); | |
if (delta < 0) return 0; | |
if (delta == 0) { | |
roots[0] = roots[1] = (-b) / (2 * a); | |
return 1; | |
} | |
roots[0] = ((-b) + sqrt(delta)) / (2 * a); | |
roots[1] = ((-b) - sqrt(delta)) / (2 * a); | |
return 2; | |
} | |
void solve_a_zero(double b, double c, double roots[4], int *count) { | |
/* since a == 0, we need to solve b^2 + c = 0 */ | |
*count = solve_quadratic(b, 0, c, roots); | |
} | |
void solve(double a, double b, double c, double roots[4], int *count) { | |
int i, i2; | |
double temp_quad_root[2], temp_xq_root[2]; | |
for (i = 0; i < solve_quadratic(a, b, c, temp_quad_root); ++i) { | |
printf("Quad root %d is %.6lf\n", i, temp_quad_root[i]); | |
/* we abuse solve_quadratic() to solve x^2 = quad_root[i] */ | |
for (i2 = 0; i2 < solve_quadratic(1, 0, -temp_quad_root[i], temp_xq_root); ++i2) { | |
printf("Root is %.6lf, pushing\n", temp_xq_root[i2]); | |
roots[*count] = temp_xq_root[i2]; | |
(*count)++; | |
} | |
} | |
} | |
double a, b, c; | |
double roots[4]; | |
int root_count; | |
int main() { | |
printf("Enter a: "); | |
scanf("%lf", &a); | |
printf("Enter b: "); | |
scanf("%lf", &b); | |
printf("Enter c: "); | |
scanf("%lf", &c); | |
if (a == 0) { | |
solve_a_zero(b, c, roots, &root_count); | |
} else { | |
solve(a, b, c, roots, &root_count); | |
} | |
if (root_count == INF) { | |
printf("Infinity roots exists\n"); | |
} else { | |
printf("%d root%s found: \n", root_count, ((root_count % 2 == 0) ? ("s") : (""))); | |
while (root_count) { | |
root_count--; | |
printf("%.6lf\n", roots[root_count]); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment