开发者

C++, equality with g++

Why this condition is never true ? Both parts of the equation are integers, so there must be equality for index = 0, 10, 20, 30, 40. I am compiling this code using g++.

for(int index = 0; index < 50; index++){

        if ( (int) (10 * (  0.1 * index)  ==  (int)(10 * ( int ) ( 0.1 * index ) ) ) )
        {
                 std::cout << "equal";
        }
}

With MSVS 2010 compiler these problems do not occur...

  0  0
  1  0
  2  0
  3  0
  4  0
  5  0
  6  0
  7  0
  8  0
  9  0
  10  10
  11  10
  12  10
  13  10
  14  10
  15  10
  16  10
  17  10
  18  10
  19  10
  20  20
  21  20
  22  20
  23  20
  24  20
  25  20
  26  20
  27  20
  28  20
  29  20
  30  30
  31  30
  32  30
  33  30
  34  30
  35  30
  36  30
  37  30
  38  30
  39  30
  40  40
  41  40
  42  40
  40  开发者_StackOverflow中文版40
  44  40
  45  40
  46  40
  47  40
  48  40
  49  40


Your parentheses are wrong:

if ( (int) (10 * (  0.1 * index)  ==  (int)(10 * ( int ) ( 0.1 * index ) ) ) )

Should be:

if ( (int) (10 * (  0.1 * index) )  ==  (int)(10 * ( int ) ( 0.1 * index ) ) )


You're comparing two floating point numbers - 0.1*index.

Have you tried printing out the individual components when they're not equal? I suspect you'll find that somewhere in the equation, the results vary.


It's because in the second part you have ( int ) ( 0.1 * index ). So (int) (0.1 * 5) becomes rounded to 0.


The two sides are not both integers:

10 * (0.1 * index)

is a double, and uses 0.1 that as you probably know cannot be represented exactly in IEEE754 format (the only values that can be represented exactly are integral multiples of 1/(2^n) with n>=0). To make a parallel with base 10 normally used by humans a computer sees 0.1 more or less like you see 0.3333333333333... (and you dont' have infinte paper to write down all those threes).

You should follow the advice of ybungalobill, and by the way to me seems that your problem would be a lot easier to solve using a different approach based on integer arithmetic and the modulo operator.

if (index % 10 == 0)

seems to be the test you are looking for.


try

for(int index = 0; index < 50; index++){

        if ( (int) (10 * (  0.1 * (double)index))  ==  (int)(10 * ( int ) ( 0.1 * (double)index ) ) )
        {
                 std::cout << "equal";
        }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜