Conditional check for “i == (2^8)” fails when i is 512?

后端 未结 6 1706
醉话见心
醉话见心 2021-01-04 00:41

Here is a small Program to print powers of 2 till 8. But it is not quitting after 8. Please explain the reason.

#include 
#include 

        
6条回答
  •  星月不相逢
    2021-01-04 01:13

    The problem is that ^ is the Bitwise XOR operator, not raise to power. Let's explain 2^8 in bitwise format:

    2 = 0010
    8 = 1000
    ======== xor
    10= 1010
    

    so the result, applying xor bit by bit, is 10, that never happens so your loop never exits. You can make your unit test working if you use pow(2,8) and round to integer instead.

    Another information, it is probably not the case in this example, but it is better to avoid the strict equality when working with floating point values, compare with an epsilon is better.

    For your edit: Ensure the precedence with this:

    if((2^8) == (1<<8))
    

    this will return false, as expected.

提交回复
热议问题