Squaring a number in C++ yields wrong value

后端 未结 3 1248
臣服心动
臣服心动 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:50

    Edit - This is another solution to the problem; what this will do is cast the integer values to a long long before the multiplication so you don't get truncation of bits.

    Original Posting

    int n = 100000;
    long long x = static_cast( n ) * static_cast( n );
    

    Edit - The original answer provided by Jossie Calderon was already accepted as a valid answer and this answer adds another valid solution.

提交回复
热议问题