【问题标题】:CGFloat division crashCGF 浮点除法崩溃
【发布时间】:2015-01-03 13:35:03
【问题描述】:

我有这个代码:

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    NSLog([NSString stringWithFormat:@"\n%g pixel \n=======================================",screenWidth]);
    CGFloat imageWidth = [[self.widthArray objectAtIndex:indexPath.row] floatValue];
    NSLog([NSString stringWithFormat:@"\n%f pixel\n=======================================",imageWidth]);
    CGFloat ratio = screenWidth / imageWidth;
    NSLog([NSString stringWithFormat:@"\nratio is %f\n=======================================",ratio]);

screenWidthimageWidth 完全没问题,但是当我尝试记录 ratio 时,程序会崩溃并且日志显示 (lldb)。我还没有在任何地方找到解决方案。有什么建议吗?

编辑:

前两个日志是

2015-01-03 08:49:00.888 Huckleberry[6554:158359] 
320.000000 pixel 
=======================================
2015-01-03 08:49:00.889 Huckleberry[6554:158359] 
512.000000 pixel
=======================================

然后ratio 就是(lldb)

【问题讨论】:

  • 1.价值观是什么? 2.研究NSLog(),没必要用stringWithFormat。例如:NSLog(@"\n%g pixel\n=======================================", screenWidth);
  • 研究NSLog(),没必要用stringWithFormat。例如:NSLog(@"\n%g pixel\n=======================================", screenWidth);。此外,NSLog() 的格式字符串应该是文字,Xcode 甚至会对此发出警告。
  • 对于 32 位平台 CGFLoat 定义为 float,对于 64 位平台 CGFLoat 定义为 double
  • 它是崩溃还是你只是在那行有一个断点?

标签: objective-c operators cgfloat


【解决方案1】:

如果您在控制台中看到(lldb),您很可能遇到了断点。如果您自己没有在那里添加断点,那么您的项目中可能有一个异常断点,用于捕获所有未捕获的异常。

尝试点击控制台上方的“播放”按钮,这应该会继续执行(或者至少可以帮助您解决崩溃的问题)。

【讨论】:

    【解决方案2】:
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    NSLog(@"Screen width = %f pixel", (float) screenWidth);
    CGFloat imageWidth = [[self.widthArray objectAtIndex:indexPath.row] floatValue];
    NSLog(@"Image width = %f pixel", (float) imageWidth]);
    CGFloat ratio = screenWidth / imageWidth;
    NSLog(@"ratio is %f", (float) ratio]);
    

    【讨论】:

    • 这不是问题的答案。这是很好的代码清理,但它没有解释任何内容或解决问题中的问题。
    • @rmaddy - 它修复了格式字符串中的操作数长度问题。
    • 但不存在操作数长度问题。 %f 可以与floatdouble 一起使用。
    猜你喜欢
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 2011-10-25
    • 2021-08-23
    相关资源
    最近更新 更多