Thread: Assignment Statements

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    4

    Assignment Statements

    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?

  2. #2
    Registered User Sake's Avatar
    Join Date
    Jan 2005
    Posts
    89
    Yes, though you'll probably get a warning telling you that it's not safe. You can silence the warning with a cast.
    Code:
    int i = static_cast<int>(123.456);
    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.

    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.
    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;
    }
    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 <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!

  3. #3
    Registered User
    Join Date
    Feb 2005
    Posts
    4
    Thank you for showing the different way. This explains a lot.^^

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Menu
    By Krush in forum C Programming
    Replies: 17
    Last Post: 09-01-2009, 02:34 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Replies: 1
    Last Post: 10-27-2006, 01:21 PM
  4. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  5. Replies: 1
    Last Post: 05-26-2006, 08:13 AM