简体   繁体   中英

for loop does not execute correctly in C

The for loop in the following function does not seem to store correctly. The value that returns for range_angle is the very first value, which I know is not correct. Also, my compute_landing_distance function (not shown here) works just fine, so it must be something in the for loop:

for (theta_l_deg=22.5; theta_l_deg<=83;.01)
{
    x_f = compute_landing_distance(v0,theta_l_deg);

    if (x_f > range_distance)
    {
        range_distance = x_f;
        range_angle = theta_l_deg;
    }

    else
    {
    break;
    }
}

return range_angle;

I want this loop to run from theta_l_deg = 22.5 to 83 in increments of .01 , and return the largest value for range_angle in that range. Also, I am aware that C only calculates in radians, and the compute_landing_distance function takes that into account.

for (theta_l_deg=22.5; theta_l_deg<=83;.01)

should be

for ( theta_l_deg = 22.5 ; theta_l_deg <= 83 ; theta_l_deg += 0.01 )

In your original code, you are not incrementing the value of theta_l_deg

for (theta_l_deg=22.5; theta_l_deg<=83; theta_l_deg+=0.01)
{
    x_f = compute_landing_distance(v0,theta_l_deg);

    if (x_f > range_distance)
    {
        range_distance = x_f;
        range_angle = theta_l_deg;
    }

    else
    {
    break;
    }
}

return range_angle;

Wrong for loop, missing increment

for (theta_l_deg=22.5; theta_l_deg<=83;.01)

should be

for (theta_l_deg=22.5; theta_l_deg<=83; theta_l_deg += .01)

Read http://floating-point-gui.de/ and notice that 0.01 is not exactly representable as IEEE754

BTW, you should compile with all warnings and debug info: gcc -Wall -Wextra -g if using GCC .

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