The code is supposed to approximate a root of a cubic function where coefficient 'a' is always 1 using newtons method of approximation after reading and storing the info from a .dat file.

// Assignment 1.cpp : Defines the entry point for the console application. // Use Newton/Raphson's method to approximate the roots of a cubic function #include "stdafx.h" #define a 1 /* coefficients */ double b; /* coefficients */ double c; /* coefficients */ double d; /* coefficients */ double x; /* intial guess */ double root_x ; /* root of x */ int count_rep; /* function prototype */ double newtons_method(double, double, double, double); double first_derivative(double, double, double); int main(void) { /* the input file - alternate method */ printf("input data as follows; a, b, c, d, guess ->"); scanf("%lf %lf %lf %lf", &b, &c, &d, &x); /* pointer to the file */ FILE *ptr; /* creating the file and pointing to it */ ptr = fopen("input1.dat", "r"); /* if theres an error in reading file or the files is empty */ if( ptr == NULL) printf("File read error!"); /* store the data on the file to memory */ fscanf(ptr, "%lf %lf %lf %lf", &b, &c, &d, &x); /* See if the first derivative equals zero as this would give an error */ if ( first_derivative(b, c, x) == 0 ) { printf("Error, first derivative equals zero. Make a new initial guess"); printf("Enter new inital guess>"); scanf("lf", &x); /* checking the first derivative is far enough away from zero for a result */ } else if ( first_derivative(b, c, x) <= 0.5 && first_derivative(b, c, x) >= -0.5 ) { printf("Error, first derivative is too close to zero to cause convergence. Make a new initial guess"); printf("Enter new inital guess>"); scanf("lf", &x); /* if no error is found, execute function 'newtons_method' and loop until a result is found */ } else { count_rep = 0; while (count_rep <=20 && (root_x - x <= -0.000005 && root_x - x >= 0.000005)) { newtons_method(b, c, d, x); count_rep = count_rep + 1; } printf("The cubic polynomial; a equals %f, b equals%f, c equals%f, d equals%f\n, With an intital guess of%f.\n", a, b, c, d, x); printf("Gives F(x)=0 at x=%f..... root found after %d iterations", count_rep); return 0; } double newtons_method(double b, double c, double d, double x) { root_x = (x - (( a * (x * x * x) + b * (x * x) + c * x + d ) / (3 * (x * x) + 2 * b * x + c))); return(root_x); } /* finds the first derivative of a function with an assumed 'a' coefficients of one * input - b and c coefficients and x value * outputs and replaces the x value with the first derivative of the input value */ double first_derivative(double b, double c, double x) { return(3 * (x * x) + 2 * b * x + c); }