converting double to int

This is a discussion on converting double to int within the C++ Programming forums, part of the General Programming Boards category; Hi everyone... I was wondering if there is a way to convert a double value to an int value. What ...

  1. #1
    Unregistered
    Guest

    converting double to int

    Hi everyone...

    I was wondering if there is a way to convert a double value to an int value.

    What i'm trying to do is to find the ceiling of an integer divided by 2.

    Code:
    #include<math.h>
    
    int num = 5;
    
    double value = ceil(5/2);
    
    //int ceiling = value            ///I want to do this.....
    Thank you!!

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    That's legal in C++. The compiler probably issues a warning, which you can get rid of by making the cast explicit.

    int ceiling = (int) value;
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  3. #3
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913
    But beard in mind that 4.99999 will yield 4 in this situation. There's no rounding - just cutting off the decimal portion.

  4. #4
    Registered User
    Join Date
    Jan 2002
    Posts
    559
    You could add .5 to the double named value and use floor() to round off, or subtract .5 and use ceil().
    4.9 + .5 = 5.4, which will floor() to 5.0
    Even if you ceil() or floor() a double, it's not an int; the value is 2.0, or 3.0, or whatever, not 2 or 3. Use the cast like SilentStrike said.
    Truth is a malleable commodity - Dick Cheney

  5. #5
    Registered User Sekti's Avatar
    Join Date
    Feb 2002
    Posts
    163
    look in the function list at cprogramming theres one to round it off then turn it into an int
    +++
    ++
    + Sekti
    ++
    +++

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, 10:42 PM
  2. Working with random like dice
    By SebastionV3 in forum C++ Programming
    Replies: 10
    Last Post: 05-26-2006, 10: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, 07: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, 04:00 PM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM

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