How to use fmod and avoid precision issues

前端 未结 2 404
情深已故
情深已故 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:28

    In cases where you always have the same fixed decimal fraction, simply multiply by up your loop counter (by 20 in this case). When you want to access it as a double, divide by 20. In effect, you are using a hidden exponent to keep your double an integer.

    In the example, I use an integer for a loop counter, assuming it has the required precision.

    for(int i=0; i<=100; i+=1) {
      if(i % 5 == 0)
        print 'X';
      double d = (double)i / 20.0;
      // use d
    }
    

提交回复
热议问题