Why is this endless for the cycle?

I have such a cycle, and when the step (0; 1), it becomes infinite. If step [1; ..), it works well.

public interface FindMinI {
double function(double x);

static double findMinOfFuncOnInterval(int begin, int end, double step, FindMinI func)
{
    double min = Double.MAX_VALUE;

    for (int i = begin; i <= end ; i += step) {

        if(func.function(i) <= min)
            min = func.function(i);

    }
    return min;
}

}

+4
source share
3 answers

If you try to take a step between (0,1), this will be added to the int when adding to i, as a result, you will add 0in iat each iteration, which will lead to an infinite loop!

+4
source

It will be infinite, because if step 0 , then adding zero to i will do nothing. No increment means an infinite loop.

+1
source

0, 0 i, , , .

, , 0.0001. , i - , double int, 0.0001 → 0. , 1 0 , 0.

i double, .

step int,

, :

(int) (500 * 0.0001) -> 0.05 as an integer = 0

Therefore, when you add a double step with a decimal value (exclusively a decimal value) to an integer, the step becomes 0, is 0added to iand becomes infinite.

+1
source

Source: https://habr.com/ru/post/1689127/


All Articles