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

后端 未结 6 1757
醉话见心
醉话见心 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:21

    In C, the ^ operator means XOR (bitwise exclusive or).

    To get 2 to the power of 8, you need to either use a loop (res *=2 in a loop), or round the pow function in math.h (note that the math.h function returns float - and therefore won't be equal to the integer).

    The simplest method is the bitwise shift, of course.

    About the edit section:

    Welcome to the wonderful world of operator precedence. What happens is that == has higher precedence than ^, and therefore the conditional evaluates to 2^0, which is 2, which is true.

    To make it work, you need to add parentheses:

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

提交回复
热议问题