简体   繁体   中英

C code exponential calculation is giving wrong result

for int value 2,015,671 this code outputs 475,739,751

long long cube(int n)
{
return n*n*n;
}

While the correct value should be 8,189,529,329,933,957,120 but using the pow(n, 3) from <math.h> I got the correct result. If it is an overflow of long long type then why does it work for pow ? And it does not reach the MAX of long long data type 9,223,372,036,854,775,807 . What is the explanation of this behaviour?

Converting the result of an expression to a new type happens too late.

If n is an int then n*n*n is an expression involving only int s and produces an int result (some subtle implicit conversions exist for types smaller than int but it is not the main concern here).

If this result overflows, then placing it in a wider integer won't help recover the lost information.
You need to perform this conversion before computing the expression.

long long cube(int n)
{
long long r=n;
return r*r*r;
}

(or change the parameter to long long )

You have to explicitly cast int to long long int.

long long cube(int n) {
  return (long long int) n*n*n;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM