__c++ of the rounding operation in C + +

Source: Internet
Author: User
rounding a number that contains a decimal point is a common requirement. Similar rounding functions are also available in C + +. There are floor () and ceil () functions in the header file of C + +. There is also a round () function in the STL. The function of these three functions is as follows:
           
Function name Function description 2.1 2.9 -2.1 -2.9
Floor () The largest integer that is not greater than the argument 2 2 -3 -3
Ceil () The largest integer that is not less than the independent variable 3 3 -2 -2
Round () Rounded to the nearest adjacent integer 2 3 -2 -3

As you can see from the description of the function,
(1) Floor () takes the largest integer not greater than the argument, so that the argument is 3.1 or 3.9 is no different, the return is 3; The argument is-2.1 or-2.9 is no different, and the return is-3;
(2) Ceil () takes the largest integer that is not less than the argument, so that the argument is 3.1 or 3.9, the return is 4, the argument is-2.1 or-2.9, and the return is-2;
(3) The Round () function, which is the rounded function we need, because it returns the nearest integer from the variable, the returned integer may or may be less than the original number, but it must be the nearest integer.

Note: Floor (), the Ceil () function is included in the header file "Math.h", but the round () function is not included in the header file. So you can implement the round () function on your own by using the above principles to achieve rounding of numbers that contain decimals.

Code implementation One:

int round_double (double)
{return
    (number > 0.0)? (number + 0.5): (number-0.5); 
}
1 2 3 4 1 2 3 4

Code implementation Two:

int round_double (Double) {return (number > 0.0)? floor (number + 0.5): Ceil (number-0.5);} 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.