Thread: round .5

  1. #16
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    Quote Originally Posted by iMalc View Post
    Consider 1.55555555 instead.
    The answer with rounding should be 1.56, not 1.55
    times 100

    1.5555 * 100 = 155.55

    round

    156

    divide by 100

    1.56
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  2. #17
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by iMalc View Post
    Consider 1.55555555 instead.
    The answer with rounding should be 1.56, not 1.55
    And conveniently, that's what you get. (Or at least that's what I got, when I did it.)

  3. #18
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    And of course, it should be noted that due to the inaccuracy of floats, you still might not get exactly the answer you expect.

    For instance, round( 1.234 * 100.0 ) / 100.0 might give 1.229999999, which would be printed as 1.22 if you are limiting the number of digits.

    But that's just the way the cookie crumbles.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  4. #19
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Bleh - brainfart. For ome reason I thought it didn't mention rounding.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #20
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    838
    Code:
    int round(double f)
    {  
      unsigned int i = fabs(f*2);
      if(i&1)
      {
        if(f>0)
        {
          return (int)++f;
        }
        return (int)--f;
    
      }
      else
      {
        return (int)f;
      }
    }
    i don't have a need for rounding to a particular number of decimal points, just to intelligently convert floats into ints.

    this seems to do the trick, but i thought i'd throw it up in case someone can spot a problem.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  2. Fibonacci Formula, How to round in C++?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 10-15-2004, 10:47 AM
  3. I need some quick help with code.
    By stehigs321 in forum C Programming
    Replies: 35
    Last Post: 10-30-2003, 10:07 PM
  4. Someone help me with this game??
    By stehigs321 in forum Game Programming
    Replies: 15
    Last Post: 10-30-2003, 09:42 PM
  5. Please help with some coding..
    By stehigs321 in forum C Programming
    Replies: 2
    Last Post: 10-27-2003, 06:44 PM