The principle of printf rounding in GCC

Source: Internet
Author: User

    • VC + + is using the Round half away from zero
    • GCC is using the Round half to even which is also known as banker ' s rounding.

    • Nearest integer function in computer science, the Nearest integer function of real number x denoted variously by Round (x), is a function which returns the nearest an integer to X. To avoid ambiguity if operating on half-integers, a rounding rule must be chosen. On most computer implementations, the selected rule was to round half-integers to the nearest even Integer-for example,

Test program on gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.2)

#include <iostream> #include <vector> #include <stdio.h> #include <algorithm>using namespace Std;void printvector (float& elem) {    printf ("Value%f is change to%0.1f \ n", Elem, Elem);} void Testroundrules () {    cout << "using gcc" << Endl;    Float fvalues[] = {3.05f, 3.15f, 3.151f, 3.155f, 3.25f, 3.251f, 3.255f,-0.45f, -0.15f};    Using the vector's constructor, copy the first element of the array from the beginning to the end of the content to the vector    vector<float> vdatas (fvalues, fvalues+sizeof (fvalues)/ sizeof (Fvalues[0]));    For_each (Vdatas.begin (), Vdatas.end (), printvector);}

  

Output

Using GCC

Value 3.050000 is change to 3.0
Value 3.150000 is change to 3.2
Value 3.151000 is change to 3.2
Value 3.155000 is change to 3.2
Value 3.250000 is change to 3.2
Value 3.251000 is change to 3.3
Value 3.255000 is change to 3.3
value-0.450000 is Change to-0.4
value-0.150000 is Change to-0.2

Note that 3.251 was rounding to 3.3 not 3.2, because 3.3 was nearer to 3.251.

The principle of printf rounding in GCC

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.