xcode CGFloat 地板到 NSInteger
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31687285/
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
CGFloat floor to NSInteger
提问by Dave
In Xcode, the compiler is complaining about the following cast:
在 Xcode 中,编译器抱怨以下强制转换:
CGFloat width = 5.6f;
NSInteger num = (NSInteger)floor(width);
CGFloat width = 5.6f;
NSInteger num = (NSInteger)floor(width);
Saying "cast from function call of type 'double' to non-matching type 'NSInteger' (aka 'int')"
说“从'double'类型的函数调用转换为非匹配类型'NSInteger'(又名'int')”
One workaround would be to simply cast the CGFloat to NSInteger which truncates but I want to make the code clear/easy to read by explicitly flooring. Is there a function for flooring that returns an int? Or some other (clean) way of doing this?
一种解决方法是简单地将 CGFloat 转换为 NSInteger 截断,但我想通过显式地板使代码清晰/易于阅读。是否有返回 int 的地板函数?或者其他一些(干净的)方式来做到这一点?
My compiler settings under "Apple LLVM 6.0 - Compiler Flags", in "Other C Flags", I have -O0 -DOS_IOS -DDEBUG=1 -Wall -Wextra -Werror -Wnewline-eof -Wconversion -Wendif-labels -Wshadow -Wbad-function-cast -Wenum-compare -Wno-unused-parameter -Wno-error=deprecated
我在“Apple LLVM 6.0 - Compiler Flags”下的编译器设置,在“Other C Flags”中,我有-O0 -DOS_IOS -DDEBUG=1 -Wall -Wextra -Werror -Wnewline-eof -Wconversion -Wendif-labels -Wshadow -Wbad -function-cast -Wenum-compare -Wno-unused-parameter -Wno-error=deprecated
Thanks!
谢谢!
回答by Palle
Okay, as you mentioned strict compiler settings, I tried again and found the solution.
The compiler warning is because you are trying to cast the floor function to a NSInteger value and not the returned value.
To solve this, all you have to do, is to put floor(width) in parentheses like this:
好的,正如你提到的严格的编译器设置,我再次尝试并找到了解决方案。编译器警告是因为您试图将 floor 函数转换为 NSInteger 值而不是返回值。
要解决这个问题,您所要做的就是将 floor(width) 放在括号中,如下所示:
NSInteger num = (NSInteger) (floor(width));
or save the result of the floor operation to another CGFloat and cast the new variable to NSInteger
或者将 floor 操作的结果保存到另一个 CGFloat 并将新变量转换为 NSInteger
CGFloat floored = floor(width);
NSInteger num = (NSInteger) floored;
回答by TheSD
Use floorf()
for floats. So NSInteger num = (NSInteger)floorf(width);
使用floorf()
的浮动。所以NSInteger num = (NSInteger)floorf(width);
More information CGFloat-based math functions?