【发布时间】:2016-02-02 00:56:40
【问题描述】:
您如何将浮点值四舍五入,让我们说小数点后的单个数字到例如给定 18.0-18.4 我想显示 18.0 或给定 18.5-19.0 显示 19.0 等? 谢谢大家
【问题讨论】:
标签: c++ floating-point numbers
您如何将浮点值四舍五入,让我们说小数点后的单个数字到例如给定 18.0-18.4 我想显示 18.0 或给定 18.5-19.0 显示 19.0 等? 谢谢大家
【问题讨论】:
标签: c++ floating-point numbers
使用std::round()@Revolver_Ocelot评论的@
使用floor(x + 0.5) 有失败的情况:
负数。当然,代码可以为此尝试ceil(x - 0.5)。
总和 x+0.5 可能会创建一个新整数的舍入答案:FP 数刚好小于 0.5。 x 的 ULP(最低意义的二进制数字)为 0.5 或 1.0 的一些值。
IOW,代码需要确保 0.5 加法不需要额外的精度。
下面是候选round_alt() 应该round() 不存在。 round_alt() 没有这些问题。
double round_alt(double x) {
double ipart;
// break into integer and fraction parts
double fpart = modf(x, &ipart);
if (fpart != 0.0) {
if (x >= 0.5) {
ipart += floor(fpart + 0.5);
} else if (x <= -0.5) {
ipart += ceil(fpart - 0.5);
}
}
return ipart;
}
【讨论】:
我会使用 floor() 函数。因为你的编译器可能没有实现 round()。
#include "stdafx.h"
#include <math.h>
int _tmain(int argc, _TCHAR* argv[])
{
double input = 18.0;
for (int i = 0; i < 10; i++, input += 0.1 )
{
double output = floor( input + 0.5 );
printf( "Input:%f Output:%f\n", input, output );
}
getchar();
return 0;
}
输出是这样的。
【讨论】:
round() 的 C 或 C++ 编译器。