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.

转载于:https://my.oschina.net/aquar/blog/731999

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值