C++ 为什么 round() 和 ceil() 不返回整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1253670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do round() and ceil() not return an integer?
提问by Wookai
Once in a while, I find myself rounding some numbers, and I always have to cast the result to an integer:
偶尔,我发现自己对一些数字进行了四舍五入,而且我总是不得不将结果转换为整数:
int rounded = (int) floor(value);
Why do all rounding functions (ceil()
, floor()
) return a floating number, and not an integer? I find this pretty non-intuitive, and would love to have some explanations!
为什么所有舍入函数 ( ceil()
, floor()
) 都返回浮点数,而不是整数?我觉得这很不直观,很想得到一些解释!
回答by Sean A.O. Harney
The integral value returned by these functions may be too large to store in an integer type (int, long, etc.). To avoid an overflow, which will produce undefined results, an application should perform a range check on the returned value before assigning it to an integer type.
这些函数返回的整数值可能太大而无法存储在整数类型(int、long 等)中。为避免溢出,这将产生未定义的结果,应用程序应在将返回值分配给整数类型之前对其执行范围检查。
from the ceil(3) Linux man page.
来自 ceil(3) Linux 手册页。
回答by sharptooth
That's because float
's range is wider than int
's. What would you expect to have if the value returned by these functions did not fit into an int
? That would be undefined behaviour and you would be unable to check for that in your program.
那是因为float
的范围比 的范围更广int
。如果这些函数返回的值不适合int
? 那将是未定义的行为,您将无法在程序中检查该行为。