简体   繁体   中英

CGFloat floor to NSInteger

In Xcode, the compiler is complaining about the following cast:

CGFloat width = 5.6f; NSInteger num = (NSInteger)floor(width);

Saying " cast from function call of type 'double' to non-matching type 'NSInteger' (aka '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?

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

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.

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

CGFloat floored = floor(width);
NSInteger num = (NSInteger) floored;

Use floorf() for floats. So NSInteger num = (NSInteger)floorf(width);

More information CGFloat-based math functions?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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