0

I am stuck in problem where the double number is not getting properly converted to integer.

In this case->

int x=1000; double cuberoot=pow(x,(1/(double)3)); int a=cuberoot; cout<<"cuberoot="<<cuberoot<<endl; cout<<"a="<<a<<endl; 

Output:

cuberoot=10 a=9 

Why here a=9 and not 10?

Any solution to this problem??

Also I don't want to round the value..if a=3.67 then it should be converted to 3 only and not 4.

2
  • You can add a small positive to number and then calculate the root. Like x=1000+0.05. This would give a=10. Commented Jun 14, 2014 at 18:03
  • 1
    It is not the cube - That would be x^3 Commented Jun 14, 2014 at 18:04

2 Answers 2

1

Because the cuberoot is very close to 10 but not quite 10. std::cout truncates and rounds the number to 10, but a double to integer conversion will strip the decimal which is why a = 9. To solve this problem, you can use std::round():

int a=round(cuberoot); 
Sign up to request clarification or add additional context in comments.

7 Comments

So any solution to this so that a=10 here?
use a round() function.
Actually problem is I don't want to round exactly.
I want that if a=3.99 then it should be converted to 3 only....any solution to this?
Right now cube = 9.99... and it is converting that to a=9
|
0

Try this and see why!

#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main(){ int x = 1000; double cube = pow(x, 1.0/3.0); int a = cube; cout<<"cube="<< fixed << setprecision(16) << cube<<endl; cout<<"a="<<a<<endl; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.