简体   繁体   中英

Loop can't reach the expected endpoint

double angle = .50, stop = .59;

Console.WriteLine("  Angle   Sine     Cosine");
while (angle <= stop)
{
    CalculateSineAndCosine(angle, out sine, out cosine);
    Console.WriteLine($"{angle,6:F}{sine,10:F4}{cosine,9:F4}");
    angle += .01;
}

The last loop only get to 0.58 instead of 0.59. Can't understand what happened. Please help. PS If stop = 0.60, it will reach 0.59. But that happened when I still use <= not <

This is likely due to approximation nature with double values. double type are floating point values that are not exact. 0.01 in double is probably slightly more than 0.01. There is an excellent explanation here .

If that is the case, the last time through the loop, the angle value is slightly more than 0.58 and adding another value slightly more than 0.01 will make it more than 0.59 and exit the loop.

Read more about equality check. It is more and less same in your case.

floating point numbers equality checking

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