Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Dato: 13-10-2011
- * Kursus: Imperativ Programming
- * Underviser: Kurt Nørmark
- * Opgave: http://people.cs.aau.dk/%7Enormark/impr-c/functions-anden-grads-ex-pars-slide-exercise-1.html
- * Tid brugt: 75 minutter
- */
- #include <stdio.h>
- #include <math.h>
- // Prototyper.
- double findDiscriminant(double a, double b, double c);
- double findRootOne(double a, double b, double discriminant);
- double findRootTwo(double a, double b, double discriminant);
- void solveQuadraticEquation(double a, double b, double c);
- // Main call.
- int main(void) {
- // Initialize variables
- int a,b,c;
- // Start do while loop, if a,b,c are NOT zero continue running the loop
- do {
- // Get values.
- printf("Write values for a, b and c> ");
- scanf("%d %d %d", &a, &b, &c);
- // If a is zero it's not a quadratic equation, but that's no reason to quit.
- if (a == 0) {
- continue;
- }
- else {
- solveQuadraticEquation(a,b,c);
- }
- }
- while (!(a == 0 && b == 0 && c == 0));
- return 0;
- }
- // Solve quadratic equation. Could just move this into main, but assignment said to call it.
- void solveQuadraticEquation(double a, double b, double c) {
- if (findDiscriminant(a,b,c) < 0) {
- printf("No roots\n");
- }
- else {
- printf("The first root: %.2f\n", findRootOne(a,b, findDiscriminant(a,b,c)));
- printf("The second root: %.2f\n", findRootTwo(a,b, findDiscriminant(a,b,c)));
- }
- }
- // Find discriminant.
- double findDiscriminant(double a, double b, double c) {
- return b * b - 4 * a * c;
- }
- // Find the first root if it exists.
- double findRootOne(double a, double b, double discriminant) {
- // if the discriminant is 0 then we use a special case.
- if (discriminant == 0) {
- return -b / (2*a);
- }
- // Otherwise use this.
- else {
- return (-b + sqrt(discriminant)) / (2*a);
- }
- }
- // Find the second root if it exists.
- double findRootTwo(double a, double b, double discriminant) {
- // Get the second root
- if (discriminant > 0) {
- return (-b - sqrt(discriminant)) / (2*a);
- }
- // If it doesn't exist, set it to the same value as the first root.
- else {
- return (-b + sqrt(discriminant)) / (2*a);
- }
- }
Add Comment
Please, Sign In to add comment