简体   繁体   中英

Why is my while loop infinite?

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

int main(int argc, char **argv) {

if (argc != 2) {
    printf("Too many arguments.\n", argc );
return 1;
}

double n;
n = atof(argv[1]);

if (n<0) {
    printf("Negative argument.\n");
return 1;
}

double r;
r = n;
int iteration;
iteration = 0;

while(calcError(n,r)<1e-6) {
    iteration = iteration +1;
    r = (r + n/r)/2;
    printf("  %d. sqrt(%f)~= %f,error=%e\n",iteration,n,r,calcError(r,n));  
}

printf("sqrt(%f)=%f to  six places\n",n,r); 

return 0;
}

int calcError (double n, double r) {

double delta;

delta = n-r*r;
delta = delta > 0 ? delta : -delta;

return 0;

}

Running this code generates an infinite while loop. I also get a warning stating: format '%e' expects argument of type 'double', but argument 5 has type 'int' [-Wformat]. Why is this?

calcError always returns 0 , so

while(calcError(n,r)<1e-6)

is as good as

while(0 < 1e-6)

or

while(true)

As for the warning, the compiler says exactly what's wrong: calcError returns an int , but the format string provided by you ( %e ) need a double . This will yield Undefined Behavior. Changing the return type as below will fix this issue.

Looking at your code, I think you wanted to loop as long as the error was larger than 1e-6 . If that's correct, you might want to modify your calcError to be as follows:

int calcError (double n, double r)
{
    double delta;

    delta = n-r*r;
    delta = delta > 0 ? delta : -delta;
    return delta;
}

which can be shortened to

double calcError(double n, double r)
{
    return fabs(n-r*r);
}

and change the condition of your loop to loop until it's smaller:

while(calcError(n,r) > 1e-6)

In your calcError() function, you have,

return 0;

So in your expression, calcError() will always be zero.

and, (0 < 1e-6) is always true.

You have while(calcError(n,r)<1e-6) and calcError always returns 0, so of course your loop will go on forever. I think you meant to have calcError return delta instead of 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM