C语言 C: (int)x 和 floor(x) 之间的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2604235/
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
C: difference between (int)x and floor(x)?
提问by igul222
In C, what is the difference between these two?
在C中,这两者有什么区别?
float myF = 5.6;
printf( "%i \n", (int)myF ); // gives me "5"
printf( "%ld \n", floor(myF) ); // also "5"?
When is one preferable over the other?
什么时候一个比另一个更可取?
回答by Mark Rushakoff
One big difference is that of negative numbers; if you change myFto -5.6, then casting to an int returns -5while floor(myF)is -6.
一大区别是负数;如果更改myF为-5.6,则转换为 int 会返回-5while floor(myF)is -6。
As to which is preferable, as a rule of thumb I'd say to only cast to an int if you knowthat's what you need -- and since you're asking here, chances are that you probably want floor.
至于哪个更可取,根据经验,如果您知道那是您需要的,我会说只转换为 int - 并且既然您在这里问,那么您可能想要floor.
(Also note that with printfformatting, %ldis a long integer; a double is %lf.)
(另请注意,printf格式化时,%ld是长整数;双精度是%lf。)
回答by Jon Purdy
floor(n)returns the mathematical floor of n, that is, the greatest integer not greater than n. (int)nreturns the truncation of n, the integer whose absolute valueis no greater than that of n. Similarly, ceil(n)returns the mathematical ceiling of n, or the smallest integer not smaller than n. As AraK pointed out, the number returned by floor()or ceil()may not fit within the range of int.
floor(n)返回 的数学底数n,即不大于 的最大整数n。(int)n返回 的截断n,绝对值不大于的整数n。同样,ceil(n)返回 的数学上限n,或不小于 的最小整数n。正如 AraK 所指出的,由floor()或返回的数字ceil()可能不适合int.
回答by AraK
When you get the floorof double, that "integer" doublemay or mayn't be representable in a variable of type int.
当您获得floordouble 时,该“整数”double可能会或可能不会在 type 变量中表示int。
回答by bdl
The former casts your float value as a integer (and you're using an int specifier in the printf call).
前者将您的浮点值转换为整数(并且您在 printf 调用中使用了 int 说明符)。
The latter uses floor (from the C math lib) to return a double that has been rounded down.
后者使用 floor(来自 C 数学库)返回一个已经四舍五入的双精度值。
回答by R Samuel Klatchko
Do you want the result as an integer or a double?
你想要结果是整数还是双精度数?
If you want a integer, cast; if you want a double, use floor.
如果你想要一个整数,转换;如果你想要双倍,请使用floor.
For example, if you want to get the cosine of the value, you should just use flooras costakes a double.
例如,如果您想获得该值的余弦值,您应该使用floorascos取双精度值。
But if you wanted to use the value for exit(just picking a random API here), you should cast because exittakes an int.
但是如果你想使用 for 的值exit(只是在这里选择一个随机的 API),你应该强制转换因为exit需要一个 int。

