Is using increment (operator++) on floats bad style?

后端 未结 4 440
孤街浪徒
孤街浪徒 2020-12-08 10:45

Is it considered \"bad style\" to use the increment operator (++) on floats? It compiles just fine but I find it smelly and counter-intuitive.

The question: In what

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 11:03

    When you add a lots of 1.0 to a float, because of floating point arithmetic you might be a little off in the end

    The best way is to do

    for ( int i = 0; i < 100; i++ )
    {
         float f = 2.433f + i * 1.0f;
    

    instead of

    for ( float f = 2.433f; f < 102.433f; f += 1.0f )
    

    In the second case the floating point arithmetic error adds up and in the first case it doesn't. As certain users have pointed out in comments below adding integrals floats might not accumulate errors but in general it is a good idea to avoid it.

提交回复
热议问题