# Thread: converting to 'int' from 'double'

1. ## converting to 'int' from 'double'

How do I fix the following problem?

I am not intentionally using a double but I'm guessing the function sqrt() in the cmath library is a double because this is the line the error occurs on?

Error: converting to 'int' from 'double'

Is there a way to make the sqrt function be an int? If so, how do I do this?
Thanks. 2. Your compiler is whining because you are not explicitly casting the result of sqrt(). Try something like this:

Code:
`int result = (int)sqrt(x);`
Just be sure you understand what's happening here -- if x is not a perfect square, the result of sqrt() will not be an integer. Truncating it to an integer type may or may not be the right thing to do. 3. thank you very much. my error is gone. i appreciate it. 4. It's called Typecasting. Try it out with some other problems. :-) 5. brewbuck's example is from C, though it can be used in C++. In C++, it would be more correct to pick the appropriate cast, in this case static_cast:
Code:
`int result = static_cast<int>(sqrt(x));` 6. Originally Posted by laserlight brewbuck's example is from C, though it can be used in C++. In C++, it would be more correct to pick the appropriate cast, in this case static_cast:
Code:
`int result = static_cast<int>(sqrt(x));`
True. C-style casts are considered "unsafe" in C++ (technically they are unsafe in C as well), but for casting between numeric types I wouldn't worry too much about the difference.

Does a C-style cast from double to int obey different rounding rules than a static_cast? I don't know. 7. Does a C-style cast from double to int obey different rounding rules than a static_cast? I don't know.
As far as I know, they do the same thing as far as primitive types are concerned.

http://bytes.com/groups/c/540140-sta...-c-style-casts

Both should produce identical machine code. Popular pages Recent additions 