GCC中printf四舍五入的原则 原

莫忆往西

###GCC中printf四舍五入的原则

• VC++ is using Round half away from zero

• GCC is using 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 integer to x. To avoid ambiguity when operating on half-integers, a rounding rule must be chosen. On most computer implementations, the selected rule is 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};
// 使用vector的构造函数，将数组第一个元素开始到结束的内容拷贝到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 is rounding to 3.3 not 3.2, because 3.3 is nearer to 3.251.

莫忆往西

java保留小数点后四舍五入的问题

2017/10/11
0
0

simpower
2018/06/21
0
0
C语言里面%2d 意思

2012/03/09
7K
0
Linux编译工具：gcc入门

1. 什么是gcc gcc的全称是GNU Compiler Collection，它是一个能够编译多种语言的编译器。最开始gcc是作为C语言的编译器（GNU C Compiler），现在除了c语言，还支持C++、java、Pascal等语言。...

zjy900507
2018/05/09
0
0
Linux编译器GCC的使用

2012/03/09
447
0

/** * 观察DOM是否发变化的事件 * @type {MutationObserver|*} */var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserv......

lwkai
21分钟前
1
0

akane_oimo
23分钟前
2
0
Oracle学习日志-6（聚合查询)

25分钟前
1
0

http://www.zhanshaoyi.com/9132.html

30分钟前
1
0

51分钟前
5
0