Converting from double to int

This is a discussion on Converting from double to int within the C++ Programming forums, part of the General Programming Boards category; Previously I have declared b as a double and I now I want to convert back to int. Here is ...

  1. #1
    T-Mac wiz23's Avatar
    Join Date
    Apr 2005
    Location
    Houston
    Posts
    48

    Converting from double to int

    Previously I have declared b as a double and I now I want to convert back to int. Here is the code:
    Code:
    int c = static_cast<int>(b);
    Does this mean that now b is now a int where c = b? Am I right?

  2. #2
    Registered User
    Join Date
    Sep 2004
    Posts
    719
    Code:
    double b = 2.5764;
    int c = 0;
    c = (int)b;   //the int tells the comiler that you MEANT to convert from a double to and int
                      //and the compiler won't warn you that you are losing some precision in the conversion
    
    // c == 2 == true
    // b == 2.5764 == true;

    edit: actually "(int) b" means evaluate 'b' as an integer
    Last edited by misplaced; 04-13-2005 at 04:27 AM.
    i seem to have GCC 3.3.4
    But how do i start it?
    I dont have a menu for it or anything.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Does this mean that now b is now a int where c = b?
    Code:
    double b = 3.5;
    int c = static_cast<int>(b);
     
    cout<<c<<endl;  //3
    cout<<b<<endl;  //3.5
    c != b

    In addition, you might think you have 3.0 in a double variable, but really you have 2.9999999999999, and when you cast that to an int, you will get 2, and 2 != 2.99999999.
    Last edited by 7stud; 04-13-2005 at 04:55 AM.

  4. #4
    Chief Code Coloniser!
    Join Date
    Apr 2005
    Posts
    121
    Does this mean that now b is now a int where c = b? Am I right?
    No, that statement takes the value of b, casts it to an int without changing the value of b, and stores that value in another variable c.

    Therefore, c is an int, and b is still a double.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Working with random like dice
    By SebastionV3 in forum C++ Programming
    Replies: 10
    Last Post: 05-26-2006, 09:16 PM
  3. Converted from Dev-C++ 4 to Dev-C++ 5
    By Wraithan in forum C++ Programming
    Replies: 8
    Last Post: 12-03-2005, 06:45 AM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 04:26 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21