请教c语言中round函数对于.5到底是四舍五入还是偶数方向舍入?

sinosinux 2011-05-17 09:38:59
大家好!

查了下man round

The round functions will return a rounded integer in the specified format that will be rounded to the nearest integer regardless of the current rounding mode.
会向最近的整数舍入,但是没有提.5离左右的两个整数距离一样时如何舍入。

查了下gcc的文档:
Without any explicit options, GCC assumes round to nearest or even and does not care about signalling NaNs. Compare with C99's #pragma STDC FENV ACCESS OFF。
意思是向偶数方向舍入。但是如下代码,测试结果表明,都是进行了四舍五入。

请问这是怎么回事,谢谢;)


printf("0.5 %f\n", round(0.5));
printf("1.5 %f\n", round(1.5));
printf("2.5 %f\n", round(2.5));
printf("3.5 %f\n", round(3.5));
printf("4.5 %f\n", round(4.5));
printf("5.5 %f\n", round(5.5));
printf("6.5 %f\n", round(6.5));
printf("7.5 %f\n", round(7.5));
printf("8.5 %f\n", round(8.5));
printf("9.5 %f\n", round(9.5));
...全文
974 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
失散糖 2011-05-18
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 zhao4zhong1 的回复:]
引用 3 楼 q191201771 的回复:
想起了赵老师
要迷信编译器

虽然“赵老师”暂时离去了,但他的话语永远留在了我们心中。三鞠躬……(^_^)

C/C++ code
//Round(1.234,2) = 1.23
//Round(1.234,0) = 1.0
//Round(123.4,-1) = 120.0
double Round(double dVal, sh……
[/Quote]

额,我以为赵老师就是指赵中呢...
赵4老师 2011-05-18
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 q191201771 的回复:]
想起了赵老师
要迷信编译器
[/Quote]
虽然“赵老师”暂时离去了,但他的话语永远留在了我们心中。三鞠躬……(^_^)
//Round(1.234,2) = 1.23
//Round(1.234,0) = 1.0
//Round(123.4,-1) = 120.0
double Round(double dVal, short iPlaces) {
double dRetval;
double dMod = 0.0000001;
if (dVal<0.0) dMod=-0.0000001;
dRetval=dVal;
dRetval+=(5.0/pow(10.0,iPlaces+1.0));
dRetval*=pow(10.0,iPlaces);
dRetval=floor(dRetval+dMod);
dRetval/=pow(10.0,iPlaces);
return(dRetval);
}

double round(double dVal, short iPlaces) //iPlaces>=0
{
unsigned char s[20];
double dRetval;

sprintf(s,"%.*lf",iPlaces,dVal);
sscanf(s,"%lf",&dRetval);
return (dRetval);
}

以下这句摘自MSDN98 VB6中文帮助:
当小数部分恰好为 0.5 时,Cint 和 CLng 函数会将它转换为最接近的偶数值。例如,0.5 转换为 0、1.5 转换为 2。
就想叫yoko 2011-05-17
  • 打赏
  • 举报
回复
想起了赵老师
要迷信编译器
AnYidan 2011-05-17
  • 打赏
  • 举报
回复
lz 因何不信自己呢?
ryfdizuo 2011-05-17
  • 打赏
  • 举报
回复
考虑0.5,自己写一个函数
int myRound(float float_v)
{
return (int)(float_v + 0.5);
}

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧