1
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. P.S. If stop = 0.60, it will reach 0.59. But that happened when I still use <= not <

D Stanley
  • 149,601
  • 11
  • 178
  • 240
Marcus Ho
  • 11
  • 1
  • 1
    Floating point arithmetic is weird. You can use an integer instead (e.g. 50 through 59) for the stop check and then just pass `intAngle / 100.0` to your `CalculateSineAndCosine()` method. – itsme86 Nov 26 '19 at 00:23

2 Answers2

0

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.

Alex W
  • 3,283
  • 1
  • 19
  • 25
0

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

floating point numbers equality checking

anuplohiya
  • 46
  • 3