Squaring a number in C++ yields wrong value

后端 未结 3 1397
臣服心动
臣服心动 2021-01-05 02:14

If I do

 int n = 100000;
 long long x = n * n;

then x == 1410065408

1410065408 is 2^31, yet I expect x to be 64 bit

3条回答
  •  半阙折子戏
    2021-01-05 02:52

    Declaring n as a long long is the best solution as mentioned previously.

    Just as a quick clarification to the original post, 1410065408 is not 2^31, the value comes about as follows:

    100,000 ^ 2 = 10,000,000,000 which exists in binary form as:

    10 0101 0100 0000 1011 1110 0100 0000 0000

    C++ integers are strictly 32 bits in memory. Therefore, the front two bits are ignored and the value is stored in memory as binary:

    0101 0100 0000 1011 1110 0100 0000 0000

    In decimal, this is equal to exactly 1410065408.

提交回复
热议问题