简体   繁体   中英

do..while loop not stopping

I am trying to create interval semi diving method (numerical method) and in the program there is a do/while loop, which does not work correctly:

double Funkcija(double x){
    double result = -1/(1+abs(x));
    return result;
}

...

double x[20] = {};
x[0] = 1; //initial point
int k = 1;  // index (from 1 because 0 is giving (x0)
do
{
    cout << "x[" << k << "]= ";
    x[k] = x[k - 1] - pow(2, k - 1)*abs(d);
    cout << x[k] << "\t";
    cout << "f(x[" << k << "])= " << Funkcija(x[k]) << endl;
    k++;
} while (Funkcija(x[k]) < Funkcija(x[k-1]));

what I get is:

在此处输入图片说明

I need that loop stop before x[4] , because f(x[3]) > f(x[2]), maybe someone see my error?

It's an "off by one" error. You have incremented k before the loop test, so you are testing the wrong indices - compare the elements at k - 1 and k - 2 and everything should be fine.

Note that if you had single-stepped through the code in your debugger, inspecting variables as you go, then the mistake would have quickly become apparent. This is an important skill to work on when you are learning to program.

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