-2

How can one increment in a for loop such that:

for (int j = 0; j < 1.0; j+=0.01) {}

Immediately I know that having a decimal makes the use of int odd.

EDIT:

Before anybody gets cheeky, I already know int is incorrect...the question is how to perform the method since int is not a valid manner to do so.

4 Answers4

8

I would advise not doing this and use an integer instead. Floating point math is weird and can give you undesired results. Using your range for example we could use

for (int i = 0; i < 100; ++j)
{
    double step = static_cast<double>(i) / 100;
}

This guarantees we get 100 iterations but still allows you to get a decimal "step" for each iteration.

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
3

Either use double and accept the accumulating errors, or use int in fixed point form, so you can compute a more accurate value on each loop.

With double:

for (double j = 0; j < 1.0; j+=0.01) {}

With fixed point to get maximum accuracy:

for (int i = 0; i < 100; ++i) {
    double j = i / 100.0;
}
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

Use a floating point type instead of an integral type.

for (float j = 0; j < 1.0; j+=0.01) {}

or

for (double j = 0; j < 1.0; j+=0.01) {}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

Since the type of j is int, the result of any arithmetic you do on it will be truncated to an integer value. So those increments will have no effect. If you change the type of j to double thing will work more like you expect. Keep in mind, though, that 0.01 can't be represented exactly as an IEEE floating-point value (which is what your hardware almost certainly uses).

Pete Becker
  • 74,985
  • 8
  • 76
  • 165