隐式转换失去了浮点精度:' double'到'漂浮&#39 ;;固定?

时间:2014-08-06 11:38:39

标签: ios implicit-conversion

我已经下载了似乎有一些错误的CMUnistrokeGestureRecognizer,我正在尝试修复它们,其中一个错误是Implicit conversion loses floating point precision: 'double' to 'float'在此代码行中;

CGFloat scale = fminf(rect.size.width / pathAnalysis.pathRect.size.width, rect.size.height / pathAnalysis.pathRect.size.height);

完整的区块是;

- (CMUDBezierPathInfo)bezierPathInfoToFitRect:(CGRect)rect
{
    CMUDPathAnalysis pathAnalysis;
    pathAnalysis.pathRect = CGRectZero;
    pathAnalysis.startPoint = CGPointMake(-1.0f, -1.0f); // i.e. undefined

    CGPathApply(self.bezierPath.CGPath, &pathAnalysis, CMUDCGPathApplierFunc);

    CGFloat scale = fminf(rect.size.width / pathAnalysis.pathRect.size.width, rect.size.height / pathAnalysis.pathRect.size.height);
    CGPoint translation = CGPointMake(-pathAnalysis.pathRect.origin.x + (rect.size.width/2.0f - scale*pathAnalysis.pathRect.size.width/2.0f),
                  -pathAnalysis.pathRect.origin.y + (rect.size.height/2.0f - scale*pathAnalysis.pathRect.size.height/2.0f));

    CMUDBezierPathInfo bezierPathInfo;
    bezierPathInfo.startPoint = pathAnalysis.startPoint;
    bezierPathInfo.scaleToFit = scale;
    bezierPathInfo.translationToFit = translation;

    return bezierPathInfo;
}

我尝试过类型转换,但它不起作用;

CGFloat scale = (CGFloat)fminf(rect.size.width / pathAnalysis.pathRect.size.width, rect.size.height / pathAnalysis.pathRect.size.height);

修改

CMDPathAnalysis定义如此;

typedef struct {
CGRect pathRect;
CGPoint startPoint;
} CMUDPathAnalysis;

2 个答案:

答案 0 :(得分:4)

当函数原型为:

时,您似乎将double类型的值传递给fminf()
float fminf(float x, float y);

因此,您传入的值会被隐式转换为float类型,因此会出现错误。

尝试使用fmin()代替fminf()fmin()采用双精度参数:

 double fmin(double x, double y);

注意CGFloat的定义是特定于体系结构的:

/* Definition of `CGFLOAT_TYPE', `CGFLOAT_IS_DOUBLE', `CGFLOAT_MIN', and `CGFLOAT_MAX'. */

#if defined(__LP64__) && __LP64__
# define CGFLOAT_TYPE double
# define CGFLOAT_IS_DOUBLE 1
# define CGFLOAT_MIN DBL_MIN
# define CGFLOAT_MAX DBL_MAX
#else
# define CGFLOAT_TYPE float
# define CGFLOAT_IS_DOUBLE 0
# define CGFLOAT_MIN FLT_MIN
# define CGFLOAT_MAX FLT_MAX
#endif

typedef CGFLOAT_TYPE CGFloat;

如果你使用的是32位架构,那么fminf()就可以了,但是为了便于携带,最好使用fmin(),除非你知道你只是要经过在float

答案 1 :(得分:1)

在Objective-C代码中,您可以使用宏MIN和MAX,它将生成与参数类型相同的结果;它们在定义YES和NO的同一头文件中定义。它们对CGFloat非常有用,它具有不同的类型,具体取决于您是编译32位还是64位。

例如:

CGFloat scale = MIN(rect.size.width / pathAnalysis.pathRect.size.width, 
                    rect.size.height / pathAnalysis.pathRect.size.height);