# converting to 'int' from 'double'

• 03-10-2009
IDK_22
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.
• 03-10-2009
brewbuck
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.
• 03-10-2009
IDK_22
thank you very much. my error is gone. i appreciate it.
• 03-11-2009
Lorgon Jortle
It's called Typecasting. Try it out with some other problems. :-)
• 03-11-2009
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));`
• 03-12-2009
brewbuck
Quote:

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.
• 03-12-2009
dwks
Quote:

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

Quote:

Both should produce identical machine code.