Im fairly new to C++ programming. My question is, Is it legal to put a double expression into an Int variable? If so what do I have to do?
This is a discussion on Assignment Statements within the C++ Programming forums, part of the General Programming Boards category; Im fairly new to C++ programming. My question is, Is it legal to put a double expression into an Int ...
Im fairly new to C++ programming. My question is, Is it legal to put a double expression into an Int variable? If so what do I have to do?
Yes, though you'll probably get a warning telling you that it's not safe.You can silence the warning with a cast.
The net result is that everything past the radix will be truncated, and i will have the value 123. But, and there's usually a "but", if you have to use a cast, you're probably doing something you shouldn't be.Code:int i = static_cast<int>(123.456);
For example, if what you want is to remove any precision from a double value, you can do it with a library function, still use doubles, and avoid any casting.
On top of that, modf also returns a normalized double for everything past the radix (0.456). Doing that with the casting method just feels icky.Code:#include <cmath> #include <iostream> using namespace std; int main() { double a = 123.456, b; cout<< modf(a, &b) <<endl; cout<< a <<'\n'<< b <<endl; }
Code:#include <iostream> using namespace std; int main() { double a = 123.456, b; int c; c = static_cast<int>(a); b = a - c; cout<< b <<endl; cout<< a <<'\n'<< c <<endl; }
Kampai!
Thank you for showing the different way. This explains a lot.^^