How to break out of a loop in c -
i'm writing bisection method algorithm find roots of polynomials. sec part of code says if fp equal 0 or absolute value of b-a
breaks if statement guess.
i want programme stop loop (iteration) exclusively , homecoming p. , @ end want print number of iteration took solution apparently using printf statement shows programme keeps executing thought root (zero) obtained.
any ideas on how stop whole mechanism , homecoming both value of p 0 , exact number of iteration took? thanks
double computeroots(double a, double b, double epsilon, int maxiter) { double fa = pow(a,4) -4*a + 1; double fb = pow(b,4) - 4*b + 1; double fp; double p; int i; for(i=0;i<maxiter;i++) { if(fa * fb < 0) { p = + (b-a)/2; fp = pow(p,4) - 4*p +1; if(fp == 0 || abs(b-a) < epsilon) { homecoming p; break; } else if (fa * fp >0) { =p; fa = fp; } else { b = p; fb = fp; } i++; } } printf("the number of iterations : %d\n", i); }
your printf
statement isn't nail because have return p;
before break
statement. return
statement exits function.
you need move return
statement after printf
, or move printf
before return
:
if(fp == 0 || abs(b-a) < epsilon) { printf("the number of iterations : %d\n", i); homecoming p; } ... printf("failed converge after %d iterations\n", i); homecoming p; }
c loops break bisection
No comments:
Post a Comment