Atheuz

Untitled

Oct 16th, 2011 (edited)
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.29 KB | None | 0 0
  1. /*
  2.  *  Dato: 13-10-2011
  3.  *  Kursus: Imperativ Programming
  4.  *  Underviser: Kurt Nørmark
  5.  *  Opgave: http://people.cs.aau.dk/%7Enormark/impr-c/functions-anden-grads-ex-pars-slide-exercise-1.html
  6.  *  Tid brugt: 75 minutter
  7.  */
  8.  
  9. #include <stdio.h>
  10. #include <math.h>
  11.  
  12. // Prototyper.
  13. double findDiscriminant(double a, double b, double c);
  14. double findRootOne(double a, double b, double discriminant);
  15. double findRootTwo(double a, double b, double discriminant);
  16. void solveQuadraticEquation(double a, double b, double c);
  17.  
  18. // Main call.
  19. int main(void) {
  20.     // Initialize variables
  21.     int a,b,c;
  22.  
  23.     // Start do while loop, if a,b,c are NOT zero continue running the loop
  24.     do {
  25.         // Get values.
  26.         printf("Write values for a, b and c> ");
  27.         scanf("%d %d %d", &a, &b, &c);
  28.  
  29.         // If a is zero it's not a quadratic equation, but that's no reason to quit.
  30.         if (a == 0) {
  31.             continue;
  32.         }
  33.         else {
  34.             solveQuadraticEquation(a,b,c);
  35.         }
  36.     }
  37.     while (!(a == 0 && b == 0 && c == 0));
  38.     return 0;
  39. }
  40.  
  41. // Solve quadratic equation. Could just move this into main, but assignment said to call it.
  42. void solveQuadraticEquation(double a, double b, double c) {
  43.     if (findDiscriminant(a,b,c) < 0) {
  44.         printf("No roots\n");
  45.     }
  46.     else {
  47.         printf("The first root: %.2f\n", findRootOne(a,b, findDiscriminant(a,b,c)));
  48.         printf("The second root: %.2f\n", findRootTwo(a,b, findDiscriminant(a,b,c)));
  49.     }
  50. }
  51.  
  52. // Find discriminant.
  53. double findDiscriminant(double a, double b, double c) {
  54.     return b * b - 4 * a * c;
  55. }
  56.  
  57. // Find the first root if it exists.
  58. double findRootOne(double a, double b, double discriminant) {
  59.     // if the discriminant is 0 then we use a special case.
  60.     if (discriminant == 0) {
  61.         return -b / (2*a);
  62.     }
  63.     // Otherwise use this.
  64.     else {
  65.         return (-b + sqrt(discriminant)) / (2*a);
  66.     }
  67. }
  68.  
  69. // Find the second root if it exists.
  70. double findRootTwo(double a, double b, double discriminant) {
  71.     // Get the second root
  72.     if (discriminant > 0) {
  73.         return (-b - sqrt(discriminant)) / (2*a);
  74.     }
  75.     // If it doesn't exist, set it to the same value as the first root.
  76.     else {
  77.         return (-b + sqrt(discriminant)) / (2*a);
  78.     }
  79. }
  80.  
  81.  
  82.  
Add Comment
Please, Sign In to add comment