Debugging and Refactoring exercise

0008.2

Definition: Debugging is the process of finding and fixing errors in program code.

Definition: Factoring (Decomposition) is the breaking of a complex task to its atomized sub parts. The goal of factoring is to reach a level of detail that can be represented in an algorithm and eventually programming code.  

Definition: Refactoring – Changing program code’s structure to improve readability or efficiency without changing it’s behavior; or, to change a code’s factoring

Instructions

Copy and paste the following code into the main.c file of  a new project:

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


int main()
{
    float a,b,c,D,root1,root2;

    printf("Please enter a value for a...\n");
    scanf("%f",a);

    printf("Please enter a value for b...\n");
    scanf("%f",&b);

    printf("Please enter a value for c...\n");
    scanf("%f",&c);

    printf("\n");

    D=(b*b)-(4*a*c);


    if(D<0)
    {
        printf("no roots\n Exiting program...\n");
    }
    else if (D=0)
    {
        root1=(b*b)/(2*a);
        printf("Equation has only one root = %.2f \n Exiting program...\n ");

    }
    else
    {
        root1=((b*b)-sqrt(D))(2*a);
        root2=((b*b)+sqrt(D))/(2*a);
        printf("Roots are %.2f and %.2f \n Exiting program...\n",root1,root2);

    }
    return 1;




}

  1. Debug your program so that it produces correct results in all cases.
  2. Modify your code to use functions.
    • Move the code for calculating the Discriminant into another function. Do this by
      • Create a new function,which returns the value of the discriminant. The new function should implement the function declaration: float discriminant (acoef,bcoef,ccoeff);
      • Change the line which contains
        D=(b*b)-(4*a*c); to D=discriminant(a,b,c);
    • Move the code for calculating root 1 and root 2 into 2 separate functions. To do this, you must create suitable function declarations and accompanying function declarations which can accomplish the task.

© 2020  Vedesh Kungebeharry. All rights reserved. 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s