2

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 multiplier.

for(double d=0.0; d<=5.0; d+=0.05) {
  if(fmod(d,0.25) is equal 0)
    print 'X';
}

This will of course not work since d will be [0, 0.05000000001, 0.100000000002, ...] causing fmod() to fail. Extreme example is when d=1.999999999998 and fmod(d,0.25) = 1.

How to tackle this? Here is an editable online example.

Mathew Block
  • 1,613
  • 1
  • 10
  • 9
c0dehunter
  • 6,412
  • 16
  • 77
  • 139
  • Unless the step size (`0.05` here) can be represented as `2**x` (** == raised to), you will not likely get `==` for float/double variables/calculations. – anishsane Feb 26 '15 at 08:20

2 Answers2

7

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3

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
}
rghome
  • 8,529
  • 8
  • 43
  • 62