Tilbage til slide -- Tastaturgenvej: 'u'  forrige -- Tastaturgenvej: 'p'                functions/eq-sec-degree-with-struct-result.c - Løsning af andengradsligning - resultater via returneret objekt af struct type.Lektion 12 - slide 17 : 36
Program 2

#include <stdio.h>
#include <math.h>

struct rootPack{
  int numberOfRoots;
  double firstRoot;
  double secondRoot;
};

typedef struct rootPack rootPack;

rootPack solveQuadraticEquation(double a, double b, double c);
void printRoots(rootPack rp);

int main(void) {
  double a, b, c;
  rootPack rp1, rp2;

  printf("Enter coeficients a, b, and c: ");
  scanf("%lf %lf %lf", &a, &b, &c);

  if (a != 0){
    rp1 = solveQuadraticEquation(a, b, c);
    printRoots(rp1);
  }
  else
    printf("The coeficient a must be non-zero");

  /* Solve another quadractic Equation */
  rp2 = solveQuadraticEquation(1.0, 1.0, -30.0);
  printRoots(rp2);

  return 0;
}


/* Find roots in the quadratic equation a * x*x + b * x + c = 0.
   Assume as a precondition that a is not zero                    */
rootPack solveQuadraticEquation(double a, double b, double c){
  rootPack result;
  double discriminant;

  discriminant = b * b - 4 * a * c;

  if (discriminant < 0){
    result.numberOfRoots = 0;
    /* result.firstRoot and result.secondRoot undefined */
  }
  else if (discriminant == 0){
    result.numberOfRoots = 1;
    result.firstRoot =  -b/(2*a);
    /* result.secondRoot undefined */
  }
  else{
    result.numberOfRoots = 2;
    result.firstRoot = (-b + sqrt(discriminant))/(2*a);
    result.secondRoot = (-b - sqrt(discriminant))/(2*a);
  }

  return result;
}   

void printRoots(rootPack rp){
  if (rp.numberOfRoots == 0)
    printf("No roots\n");
  else if (rp.numberOfRoots == 1)
    printf("One root: %f\n", rp.firstRoot);
  else 
    printf("Two roots: %f and %f\n", rp.firstRoot, rp.secondRoot);
}