2

As the title states, I'd like to start from 1 and decrement with by 0.01 all the way down to zero.

Problem is, I'm using floats and I keep getting values such as 0.5000000001.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Ogen
  • 6,499
  • 7
  • 58
  • 124
  • 2
    Please provide more context on what you are trying to achieve; perhaps `float` is not suitable for your task. – Codor May 08 '14 at 06:10
  • 2
    0.01 cannot be represented in binary float, so you should use int instead – phuclv May 08 '14 at 06:10
  • 1
    This is similar to having an `int` starting at `25` and wanting to decrement by `2.5` all the way to `0`. It isn't possible, because your decrement value isn't representable, and when you approximate it (with something that is representable), it doesn't divide your value perfectly. – Mankarse May 08 '14 at 06:11

1 Answers1

10

Simply use an int, Start at 100 decrement down to 0 and divide the value by 100.0

for (int i=100; i>=0; --i)
{    
    float f = i/100.0f;
    ...
}
xMRi
  • 14,982
  • 3
  • 26
  • 59
  • Not that performance would be limited by these operations, but it is likely to be faster to use a float index `i` going down from `100.0f` to `0.0f`. Besides, note that `float f = i/100.0;` risks making the compiler generate a double-precision division followed by a conversion to single-precision. The declaration `float f = i/100.0f;` is equivalent (for complicated reasons that the compiler may not know how to take advantage of) and more straightforward to compile. – Pascal Cuoq May 08 '14 at 08:19
  • Thank you very much, worked like a charm. – Ogen May 08 '14 at 09:33