How to use fmod and avoid precision issues

前端 未结 2 403
情深已故
情深已故 2021-01-22 12:15

I\'m going to boil this problem down to the simplest form:

Let\'s iterate from [0 .. 5.0] with a step of 0.05 and print out \'X\' for every 0.25 multipl

2条回答
  •  走了就别回头了
    2021-01-22 12:29

    I'd solve this by simply not using floating point variables in that way:

    for (int i = 0; i <= 500; i += 5) {
      double d = i / 100.0;  // in case you need to use it.
      if ((i % 25) == 0)
        print 'X';
    }
    

    They're usually problematic enough that it's worth a little extra effort in avoiding them.

提交回复
热议问题