Search code examples
c++intdoublepow

Converting double to int is giving unexpected results


I was trying to find cube root of a perfect cube using pow function but the answers were unexpected (3375 = 15^3)

#include <bits/stdc++.h>

using namespace std;

int main()
{
    double cb = pow(3375, 1.0/3.0);
    printf("cb(in double) = %lf\n", cb);
    printf("cb(in int) = %d\n",(int)cb);
    return 0;
}

the output it shows is :

cb(in double) = 15.000000
cb(in int) = 14

After discussing it with people it turned out that the code ,

printf("%0.0lf", 14.0/3);

gives output

5

I am not getting why it's happening, and if it's due to precision in storing double and rounding off, then it should round it down to a smaller value rather than rounding to a greater value.


Solution

  • TL;DR: (int)double always rounds towards zero. printf("%0.0lf", double) actually rounds to closest integer.


    When you convert the double to int, then the result is rounded towards zero. E.g. (int)14.9999 is 14, not 15. Therefore your first example with pow() must have given you the result slightly below 15, therefore direct cast to int gives 14.

    Now, when you use printf(), then other rules are used. Printf, when asked to print a double using smallest number of digits possible (%0.0lf) rounds it to the closest integer, therefore printf("%0.0lf", 14.666) prints 15.