Is this the best way to round up a float ?

This is a discussion on Is this the best way to round up a float ? within the C++ Programming forums, part of the General Programming Boards category; hi, when casting a float to an int you lose the fractional part of the number . So does the ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    84

    Is this the best way to round up a float ?

    hi,

    when casting a float to an int you lose the fractional part of the number . So does the code below round the float up to the next int in the most effective manner. If not could you please show how you would do it?

    #include <iostream>
    using namespace std;

    int main ()

    {

    double num1 = 0;
    int newnum = 0;

    cout << endl << "Please Enter a float number and i Will round it up to the next whole number!"
    << endl;

    cin >> num1;

    newnum = num1 +1;

    cout << newnum
    << endl;


    return 0;
    }

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    Why not just use the function that the language provides for this.... ciel() . You will find it in math.h or cmath(where its in namespace std)
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    154
    This comes from VB, but ought to work in c++:

    enter a float, add 0.5, then use floor() to round it out. If the float entered was x.5 or above, you'll round up. Below x.5, you'll round down.
    Telling a user to enter a float, but secretly treating it as an int, will only round down. 5.999 will come out as 5, not 6.

  4. #4
    Registered User kitten's Avatar
    Join Date
    Aug 2001
    Posts
    109
    Code:
    inline int Round(const double var)
    {
      return var > 0 ? (int)(var + 0.5) : (int)(var - 0.5);
    }
    Making error is human, but for messing things thoroughly it takes a computer

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 05-13-2009, 03:25 PM
  2. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  3. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 01:19 AM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  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