【问题标题】:floor() and ceil() functions vs casting to integer in Cfloor() 和 ceil() 函数与在 C 中转换为整数
【发布时间】:2015-02-02 20:26:51
【问题描述】:

我正在编写一些 C 代码来反复将浮点数向上和向下舍入为整数值。 标准 C 数学库包括函数 floor()ceil()。 我注意到函数的更快实现是直接转换为整数:

int up, down;
float test = 1.3548;

up = (int)(test + 1);  //ceil()
down  = (int)test;     //floor()

我做了一个快速检查,这似乎工作正常。

  1. 如果我需要将结果作为一个整数作为数组索引(即它总是返回正确的结果),这是一种可靠的向上和向下舍入方法吗?
  2. 速度显着提高是否有充分的理由? (在我的系统上,它的运行速度大约是 math.h 实现的 3 倍)

【问题讨论】:

  • 不是可靠的方法。考虑test 是整数值的情况,例如4.0。在本例中为floor(x) == ceil(x),但您的代码将返回up = 5; down = 4
  • 你确定它更快吗?向我们展示您的性能测试!
  • 取决于您所说的“可靠”。如果“可靠”意味着“它会起作用”,那么,是的。但是,如果您的意思更多,例如“它将始终向下/向上/最近/为零/等...”,那么,不...请确保在正数和负数上尝试各种方法,以及因为那些可能在int 范围之外的那些,看看会发生什么,所以你可以为你的特定情况选择“正确”的方法......哦,那可能应该是up = (int)(test + 0.5) - 想想吧......
  • 如果您不关心旧处理器,请使用 SSE4.1 进行编译。那么floor()ceil() 就不会再慢了。

标签: c casting floor ceil


【解决方案1】:

函数ceil()floor() 将返回与使用时不同的数字

up = (int)(test + 1);
down  = (int)test;

当你有一个负数时。

如果你有:

float test = -1.3548;
up = (int)test;        // ceil()
down = (int)(test-1);  // floor()

test 是整数时,即使是最后一条语句也不是计算floor() 的好方法。

除非你想以不同的方式处理正数和负数,并且test是整数的特殊情况,你最好使用ceil()floor()

【讨论】:

  • 对于round() 使用:(int)(test + 0.5f)
  • (int)(test - 1) 不等于 floor() 用于整数负数。
  • @Iggy for "for round() use: (int)(test + 0.5f)" 对于负数失败。
猜你喜欢
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
相关资源
最近更新 更多