"Int" multiplication in c++ with "long long" result [duplicate]
Asked Answered
P

2

15

I am trying to find the square of a int. My code looks like below:

long long sqr=0;
int num=77778;
sqr= num*num;

The result should have been 6049417284 But when I check the output it shows 1754449988. What is the mistake I am doing? long long should be able to store the result but why am I getting a different value?

Pause answered 10/6, 2016 at 6:0 Comment(1)
At first num*num gives an integer (and overflows), which is then implicitly casted to long long.Braggadocio
A
11

Intermediate result type is the same as first argument type in this case. So this code puts wrong value into sqr (because here you have integer overflow). Try this:

long long num = 77778;
long long sqr = num * num;

Another way with casting:

int num = 77778;
long long sqr = (long long) num * num;

To understand it better you can check these lines:

int ia = 1, ib = 2;
double da = 1.0, db = 2.0;
double ic = ia / ib; // c == 0.0, because intermediate result of division is 0
double dc = da / db; // c == 0.5, expected result
Adama answered 10/6, 2016 at 6:3 Comment(3)
I am trying to understand the mistake in my code. Shouldn't the result be getting stored properly with my code?Pause
@rowang The intermediate result before it is stored is the same as the argument types.Intrauterine
@srip, to store the result properly, it has to first compute the result properly. In your code, you are multiplying two ints. So the calculation is done in int itself. So the information is already lost before you store it into the variable.Nichol
S
7

If you multiply two integer values, the result will be an integer value. Then, the assignment of integer value to long long is meaningless.

So, to get the desired result the num should be long long also.

Salamander answered 10/6, 2016 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.