ceil/floor/rint/round,这几个C的数值处理函数,我们通常用它们来取整某个特定的浮点数。
— Function: double ceil (double x)
These functions round x upwards to the nearest integer, returning that value as a double. Thus, ceil (1.5) is 2.0.
— Function: double floor (double x)
These functions round x downwards to the nearest integer, returning that value as a double. Thus, floor (1.5) is 1.0 and floor (-1.5) is -2.0.
— Function: double rint (double x)
These functions round x to an integer value according to the current rounding mode.The default rounding mode is to round to the nearest integer; some machines support other modes, but round-to-nearest is always used unless you explicitly select another.
— Function: double round (double x)
These functions are similar to rint, but they round halfway cases away from zero instead of to the nearest integer (or other current rounding mode).
Examples:
— Function: double ceil (double x)
These functions round x upwards to the nearest integer, returning that value as a double. Thus, ceil (1.5) is 2.0.
— Function: double floor (double x)
These functions round x downwards to the nearest integer, returning that value as a double. Thus, floor (1.5) is 1.0 and floor (-1.5) is -2.0.
— Function: double rint (double x)
These functions round x to an integer value according to the current rounding mode.The default rounding mode is to round to the nearest integer; some machines support other modes, but round-to-nearest is always used unless you explicitly select another.
— Function: double round (double x)
These functions are similar to rint, but they round halfway cases away from zero instead of to the nearest integer (or other current rounding mode).
Examples:
1. 请注意rint(+/-0.5)和round(+/-0.5)之间的区别(对于+/-0.5,round函数总是返回远离0的值):
| 0.3 | 0.5 | 0.6 | -0.3 | -0.5 | -0.6 | |
| ceil | 1 | 1 | 1 | -0 | -0 | -0 |
| floor | 0 | 0 | 0 | -1 | -1 | -1 |
| rint | 0 | 0 | 1 | -0 | -0 | -1 |
| round | 0 | 1 | 1 | -0 | -1 | -1 |
2. rint和round此时相同:
| 1.3 | 1.5 | 1.6 | -1.3 | -1.5 | -1.6 | |
| ceil | 2 | 2 | 2 | -1 | -1 | -1 |
| floor | 1 | 1 | 1 | -2 | -2 | -2 |
| rint | 1 | 2 | 2 | -1 | -2 | -2 |
| round | 1 | 2 | 2 | -1 | -2 | -2 |

本文详细介绍了C语言中常用的数值处理函数,包括向上取整(ceil)、向下取整(floor)、按当前舍入模式四舍五入(rint)及默认情况下对半数情况远离零进行舍入(round)。通过具体数值的例子展示了这四个函数的不同行为,帮助读者更好地理解和应用这些函数。
34

被折叠的 条评论
为什么被折叠?



