Thread: Converting a float to an int without truncation

  1. #1
    SETmajor
    Join Date
    Jun 2004
    Posts
    2

    Question Converting a float to an int without truncation

    Hello, I am in my first two weeks of a C++ class and I am having a problem with my program.

    my program is supposed to accept five decimal numbers from the keyboard. Once these five decimal numbers are entered I must convert them into the "nearest integer" .

    I have played around with several "casting" procedures but all of them simply truncate (drop) the number after the decimal.

    I have grown frustrated and I need help.

    To whoever reads this, thanks for your time, it is greatly appreciated!!

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    give
    Code:
     float x; int y;
    and x has some value:
    Code:
    y = (int)x;
    y-=x;
    if ( y >= 0.5 )
      x++;
    Edit: Provided that the number is positive. If negitive just do the reverse
    Last edited by Thantos; 06-15-2004 at 11:07 PM.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >I have played around with several "casting" procedures

    Add 0.5, then do the casting. You could put this code into a function.

  4. #4
    SETmajor
    Join Date
    Jun 2004
    Posts
    2

    Thumbs up

    Quote Originally Posted by swoopy
    >I have played around with several "casting" procedures

    Add 0.5, then do the casting. You could put this code into a function.


    This did the trick!!

    Adding 0.5 was just what I was looking for!

    I knew I had to solve this problem with a little math but I guess I was just thinking a little to deep to see such a simple fix!!

    swoopy rules!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. linker 2019 issues
    By werdy666 in forum C++ Programming
    Replies: 3
    Last Post: 02-25-2009, 04:12 AM
  2. Debug Error Really Quick Question
    By GCNDoug in forum C Programming
    Replies: 1
    Last Post: 04-23-2007, 12:05 PM
  3. Try out my new game :) !
    By Stan100 in forum Game Programming
    Replies: 10
    Last Post: 06-05-2003, 08:10 AM
  4. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM
  5. A Simple (?) Problem
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 10-12-2001, 04:28 AM