floor() 和 ceil() 函数与在 C 中转换为整数
floor() and ceil() functions vs casting to integer in C
我正在编写一些 C 代码来反复将浮点数上下舍入为整数值。
标准 C 数学库包括函数 floor()
和 ceil()
。
我注意到函数的更快实现是直接转换为整数:
int up, down;
float test = 1.3548;
up = (int)(test + 1); //ceil()
down = (int)test; //floor()
我快速检查了一下,这似乎工作正常。
- 如果我需要结果是一个整数,作为数组索引(即它总是 return 正确的结果),这是一种向上和向下舍入的可靠方法吗?
- 速度显着提高是否有充分的理由? (在我的系统上,它的运行速度比 math.h 实施快约 3 倍)
函数 ceil()
和 floor()
将 return 与您使用
得到的数字不同
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()
。
我正在编写一些 C 代码来反复将浮点数上下舍入为整数值。
标准 C 数学库包括函数 floor()
和 ceil()
。
我注意到函数的更快实现是直接转换为整数:
int up, down;
float test = 1.3548;
up = (int)(test + 1); //ceil()
down = (int)test; //floor()
我快速检查了一下,这似乎工作正常。
- 如果我需要结果是一个整数,作为数组索引(即它总是 return 正确的结果),这是一种向上和向下舍入的可靠方法吗?
- 速度显着提高是否有充分的理由? (在我的系统上,它的运行速度比 math.h 实施快约 3 倍)
函数 ceil()
和 floor()
将 return 与您使用
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()
。