This code is pretty much all working but for some reason. It calculates the root twice before prompting the user if he wants to continue, Very strange I have looked at it a few times can't figure out why its doing this. Can someone help me w/ this problem. Maybe even show how to get it to stop doing this. Anyhow here is the code:
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define STOP 0.001
double func1 (double x);
double func2 (double x);
char q, blah,f;
double Xro, Xrn, EPS, fXro, fprimeXro;
int Iter;
void main(void)
{
FILE *outptr;
outptr=fopen("output.txt","wt");
label3: printf("\nPLease enter a value for Xro");
scanf("%lf",&Xro);
printf("\nYou entered Xro= %lf", Xro);
fprintf(outptr, "\nThe intial guess is Xro= %lf ", Xro);
Iter=1;
fprintf(outptr,"\nIter Xro Xrn error");
label1: fXro = func1(Xro);
fprimeXro = func2(Xro);
if (fprimeXro == 0.0) {
printf ("\nThe slope of a function at iteratuin number =%4d\
\nis equal to zero. Newton-Raphson Method fails. Program is\
\ngoing to prompt you to start a new initial guess!",Iter);
goto label3;
}
Xrn = Xro -fXro/fprimeXro;
printf("\nThe new estimate of the root is = %lf", Xrn);
EPS = fabs((( Xrn - Xro)/Xro)*100.);
fprintf (outptr,"\n%4d %12.9f %12.9f %12.9f\
",Iter,Xro,Xrn,EPS);
Iter = Iter + 1;
printf("Do you wish to exit, if so enter Y");
scanf("%c", &q);
if (q=='y' || q=='Y') {
return;
}
if ( EPS <= STOP ) {
printf ("\nRoot = %lf",Xrn);
fprintf (outptr,"\nRoot is = %lf", Xrn);
goto label2;
}
else {
Xro = Xrn;
goto label1;
}
label2:
fclose(outptr);
printf ("\nAre you finished using the Newton Raphson's Root finder ?");
scanf("%c", &f);
if (f=='y' || f=='Y')
return;
if (f=='n' || f=='N')
goto label3;
getch();
}
double func1(double x)
{
return( pow(x,2.0) - x -12. );
}
double func2(double x)
{
return( 2.0*x - 1.0);
}