Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

variable doesn't change its value in C++

I am a beginner in C++ and I’m writing a function that is supposed to find the closest point in a set of points ([x1,…xn]=positions_x,[y1,…yn]=positions_y) to a given point (x0,y0).

Here is my function:

double nearestPoint(double x, double y)
{
    double ind_min = 0;
    double xi = 0;
    double yi = 0;
    double dist_mini = 1000000;
    int i;
    for (i = 0; i < 50000; i=i+1)
        xi = positions_x[i];
        yi = positions_y[i];
        double a = pow(x-xi,2);
        double b = pow(y-yi,2);
            if (sqrt(a+b)<=dist_mini)
                dist_mini = sqrt(a+b);
                ind_min = i;
    return ind_min;
}

However, this always returns the exact same point. After investigation, it seems that the value of the "dist_mini" variable remains unchanged even if sqrt(a+b) is smaller. As a consequence, ind_min remains unchanged.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you have any ideas it would really helpful,

Thank you

>Solution :

Add curly brackets ({ & }) to ensure all statements are executed in the for- and if-block. Without the curly brackets, only the first statement will be inside the block.

for (i = 0; i < 50000; i=i+1)
{
    xi = positions_x[i];
    yi = positions_y[i];
    double a = pow(x-xi,2);
    double b = pow(y-yi,2);
    if (sqrt(a+b)<=dist_mini)
    {
        dist_mini = sqrt(a+b);
        ind_min = i;
    }
}
return ind_min;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading