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

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

    For your edit Section

    #include <stdio.h>
    int main()
    {
            if((2^8) == (1<<8)) {
                    printf("True.. \n");
            } else {
                    printf("False..!!");
            }
            return 0;
    }
    

    It will return False.

    0 讨论(0)
  • 2021-01-04 01:07

    ^ is not power in c, it means XOR. 2^8==10 and it will not equal to i in this code.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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) ) ...
    
    0 讨论(0)
  • ^ is bitwise XOR, the function you are looking for is pow in math.h :)

    0 讨论(0)
  • 2021-01-04 01:26

    2^8 is 2 XOR 8, ie. 10, not 256. hence your loop doesn't stop. You probably want to check against either (1<<8) or 256 specifically.

    0 讨论(0)
提交回复
热议问题