【问题标题】:CGFloat floor to NSIntegerCGF浮动地板到 NSInteger
【发布时间】:2015-07-28 21:18:28
【问题描述】:

在 Xcode 中,编译器抱怨以下转换:

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

说“从'double'类型的函数调用转换为不匹配类型'NSInteger'(又名'int')

一种解决方法是将 CGFloat 简单地转换为截断的 NSInteger,但我想通过显式地板使代码清晰/易于阅读。是否有返回 int 的地板函数?或者其他一些(干净的)方法?

我在“Apple LLVM 6.0 - 编译器标志”下的编译器设置,在“其他 C 标志”中,我有 -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 - 自定义编译器标志”中,我有: -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

标签: ios objective-c iphone xcode


【解决方案1】:

好的,正如您提到的严格的编译器设置,我再次尝试并找到了解决方案。 编译器警告是因为您试图将 floor 函数转换为 NSInteger 值而不是返回值。

要解决此问题,您所要做的就是将 floor(width) 放在括号中,如下所示:

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

或将地板操作的结果保存到另一个 CGFloat 并将新变量转换为 NSInteger

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

【讨论】:

    【解决方案2】:

    floorf() 用于浮点数。所以NSInteger num = (NSInteger)floorf(width);

    更多信息CGFloat-based math functions?

    【讨论】:

    • floorf 返回一个浮点数,我得到同样的错误:“从'float'类型的函数调用转换为不匹配类型'NSInteger'(又名'int')”
    • 很奇怪。在 C 中,将 float 转换为 int 是完全合法的...不是吗?
    • 这是因为我的编译器设置——我无法将方法的返回值直接转换为另一种类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    相关资源
    最近更新 更多