0

I was trying to find the cube root of 10^12 and used the following code in c++. To my surprise, the value returned was different . Can anyone help me with this problem.

Output: 10000 9999

    int y;
    double x=pow(1000000000000, 1./3);
    double r=floor(x);
    y=(int)r;
    cout<<x<<" ";
    cout<<y;
  • Is this a homework question or something ? We seem to be suffering from a rash of questions about `pow(x, 1./3)` lately... – Paul R Jun 11 '14 at 09:35

2 Answers2

2

Your floor operation is the issue here. What if the returned value is actually (due to precision errors) x = 9999.999? floor(x) would return 9999 while cout << x directly prints the floating point number based on it's internal precision setting, so cout << x does implicit rounding which is why 10000 is displayed there.

Try rounding x properly to an int by doing this:

int y;
double x=pow(1000000000000, 1./3);
y=(int)(x+0.5); //Proper rounding
cout<<x<<" ";
cout<<y;
return 0;
Marius
  • 2,234
  • 16
  • 18
0
double x=pow(1000000000000, 1./3);

is just bad 1/3 can not be displayed with double.

when working with double result are always interesting to say the least. 0.001 + 0.001 may just be 0.0

burner
  • 323
  • 2
  • 10
  • "[I]s just bad", "displayed with double", "always interesting", "may just be 0.0" is an assorted set of misplaced phrases. – laune Jun 11 '14 at 10:01