I'm having trouble grasping the concept of pointers. I was given the following problem.
The square root of a number N can be approximated by repeated calculation using the formula NG = 0.5( LG + N/ LG) where NG stands for next guess and LG stands for last guess. Write a function that calculates the square root of a number using this method. The initial guess will be the starting value of LG . The program will com-pute a value for NG using the formula given. The difference between NG and LG is checked to see whether these two guesses are almost identical. If they are, NG is accepted as the square root; otherwise, the next guess ( NG ) becomes the last guess ( LG ) and the process is repeated ( another value is computed for NG, the difference is checked, and so on). The loop should be repeated until the difference is less than 0.005. Use an initial guess of 1.0.
The program must be written using pointers wherever possible both in main and in all functions. Declare pointers in main for the number whose square root is to be guessed and for the approximated square root answer which will be calculated and returned/referenced back to main by the function. The function will be a void function, so the approximated square root answer must be returned/referenced to main as an output argument of the function, i.e., to an argument in the function calling statement. You must pass to the function the actual value of the number to be guessed using a pointer.
In the function, have the user enter a "guess" number which is the user's initial guess of the square root of the number passed to the function.
(sorry about the lengthy explanation, I felt I should be thorough)
I wrote the following code:
#include <stdio.h>
#include <math.h>
void fctn(double *nPtr,double *NGPtr){
double n;
nPtr=&n;
double NG;
double LG;
NGPtr=&NG;
printf("Enter guess\n");
scanf_s("%lf",&LG);
do{
NG=(.5*(LG+n/LG));
LG=NG;
}while(fabs(NG*NG-n)>.005);
}
int main(){
double *NGPtr;
double *nPtr;
printf("Enter number\n");
scanf_s("%lf",&nPtr);
fctn(NGPtr,nPtr);
double root=*NGPtr;
printf("The approximate root of the function is %f",root);
}
I was wondering if anyone had any ideas as to why it was not working? Thank you for reading.