| functions/eq-sec-degree-pars-result.c - Løsning af andengradsligning - resultater via parametre af pointertyper. | Lektion 12 - slide 17 : 36 Program 1 |
#include <stdio.h>
#include <math.h>
void solveQuadraticEquation(double a, double b, double c,
int *numberOfRoots, double *root1, double *root2);
void printRoots(int numberOfRoots, double firstRoot, double secondRoot);
int main(void) {
double a, b, c, r1, r2, s1, s2;
int nr1, nr2;
printf("Enter coeficients a, b, and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
if (a != 0){
solveQuadraticEquation(a, b, c, &nr1, &r1, &r2);
printRoots(nr1, r1, r2);
}
else
printf("The coeficient a must be non-zero");
solveQuadraticEquation(1.0, 1.0, -30.0, &nr2, &s1, &s2);
printRoots(nr2, s1, s2);
return 0;
}
/* Find roots in the quadratic equation a * x*x + b * x + c = 0.
Assume as a precondition that a is not zero */
void solveQuadraticEquation(double a, double b, double c,
int *numberOfRoots, double *root1, double *root2){
double discriminant;
discriminant = b * b - 4 * a * c;
if (discriminant < 0){
*numberOfRoots = 0;
}
else if (discriminant == 0){
*numberOfRoots = 1;
*root1 = -b/(2*a);
}
else{
*numberOfRoots = 2;
*root1 = (-b + sqrt(discriminant))/(2*a);
*root2 = (-b - sqrt(discriminant))/(2*a);
}
}
void printRoots(int numberOfRoots, double firstRoot, double secondRoot){
if (numberOfRoots == 0)
printf("No roots\n");
else if (numberOfRoots == 1)
printf("One root: %f\n", firstRoot);
else
printf("Two roots: %f and %f\n", firstRoot, secondRoot);
}