简体   繁体   English

CGFloat楼到NSInteger

[英]CGFloat floor to NSInteger

In Xcode, the compiler is complaining about the following cast: 在Xcode中,编译器抱怨以下转换:

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. 一个解决方法是简单地将CGFloat强制转换为NSInteger,但是我希望通过显式地板来清除/轻松读取代码。 Is there a function for flooring that returns an int? 是否有返回int的地板功能? Or some other (clean) way of doing this? 或者其他一些(干净的)这样做的方式?

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! 谢谢!

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. 编译器警告是因为您尝试将floor函数转换为NSInteger值而不是返回值。

To solve this, all you have to do, is to put floor(width) in parentheses like this: 要解决这个问题,你所要做的就是将地板(宽度)放在括号中,如下所示:

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;

Use floorf() for floats. 使用floorf()浮动。 So NSInteger num = (NSInteger)floorf(width); 所以NSInteger num = (NSInteger)floorf(width);

More information CGFloat-based math functions? 更多信息基于CGFloat的数学函数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM