c - C中三位数精度的快速舍入 float

标签 c rounding

我看过这段代码:

(int)(num < 0 ? (num - 0.5) : (num + 0.5))

( How to round floating point numbers to the nearest integer in C? ) 用于四舍五入,但我需要对点后的三位数字使用 float 和精度。 例子: 254.450 应四舍五入为 255。 254.432 应向下舍入为 254 254.448 应向下舍入为 254 等等。

注意:这就是我所说的“3 位数字”,即点后的粗体数字。

我相信它应该比 roundf() 更快,因为当我需要计算轮数时,我使用了数十万轮。您有一些如何做到这一点的提示吗?我试图搜索 roundf 的来源但没有找到。

注意:我需要它来实现 RGB2HSV 转换功能,所以我认为 3 位数字应该足够了。我使用正数。

最佳答案

“它应该比 roundf() 更快”只能通过分析各种方法来验证。

要舍入到 0 位(舍入到最接近的整数),请使用 roundf()

float f;
float f_rounded3 = roundf(f);
<小时/>

要使用float四舍五入到3位,请使用round()

The round functions round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction.

#include <math.h>

float f;
float f_rounded3 = round(f * 1000.0)/1000.0;

代码特意使用了double中间类型,否则代码使用缩小范围的代码:

float f_rounded3 = roundf(f * 1000.0f)/1000.0f;
<小时/>

如果代码使用 roundf() 或各种测试将 254.450 舍入为 255.0 时遇到问题,可能是因为该值为 不是 254.450,而是接近它的浮点,例如254.4499969,四舍五入为254。 典型使用二进制格式和 254.450 的 FP 无法完全表示。

关于c - C中三位数精度的快速舍入 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28384302/

相关文章:

java - 为什么 java math.round 总是四舍五入?

c - 编译 gSOAP 客户端时 undefined reference

c - 使用 free() 释放内存

c# - 如何在 C# 中四舍五入到最接近的整数

Python 百分比舍入

PHP number_format 是否四舍五入?

c - 将数组中的值分配给结构数组

c - 将多个字符串分别放入一个数组中

c - 为什么扫描时空字符不会添加到字符串末尾?

php - 为 jpeg 文件添加圆角