Objective-C浮点/双精度 [英] Objective-C Float / Double precision

查看:113
本文介绍了Objective-C浮点/双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用NSUserDefaults来存储floatdouble以便在iPhone应用程序中使用时一团糟,并且在精度如何使用它们以及如何理解它们方面遇到了一些不一致之处.

I was messing around with storing floats and doubles using NSUserDefaults for use in an iPhone application, and I came across some inconsistencies in how the precision works with them, and how I understood it works.

这完全符合我的设想:

{
    NSString *key = @"OneLastKey";
    [PPrefs setFloat:235.1f forKey:key];
    GHAssertFalse([PPrefs getFloatForKey:key] == 235.1, @"");
    [PPrefs removeObjectForKey:key];
}

但是,这不是:

{
    NSString *key = @"SomeDoubleKey";
    [PPrefs setDouble:234.32 forKey:key];
    GHAssertEquals([PPrefs getDoubleForKey:key], 234.32, @"");
    [PPrefs removeObjectForKey:key];
}

这是GHUnit给我的输出:

This is the output GHUnit gives me:

'234.320007324' should be equal to '234.32'. 

但是,如果我先将double转换为float,然后将其转换为double,则可以正常运行:

But, if I first cast the double to a float, and then to a double it works without fail:

{
    NSString *key = @"SomeDoubleKey";
    [PPrefs setDouble:234.32 forKey:key];
    GHAssertEquals([PPrefs getDoubleForKey:key], (double)(float)234.32, @"");
    [PPrefs removeObjectForKey:key];
}

我的假设是,输入的末尾没有'f'的数字已经被认为是double s.这不正确吗?如果是这样,为什么强制转换为float然后double正常工作?

I was under the assumption that numbers entered without an 'f' at the end were already considered doubles. Is this incorrect? If so, why does casting to a float and then double work correctly?

推荐答案

已解决!原来我的框架方法+(void)setDouble:(double)value forKey:(NSString*)key实际上定义为+(void)setDouble:( float )value forKey:(NSString*)key.传递给的值是的两倍,但被转换为浮点数以用于该方法.一个简单的复制和粘贴问题.不幸的是,Objective-C编译器至少没有像其他事情一样发出警告……

Solved! Turns out my framework method +(void)setDouble:(double)value forKey:(NSString*)key was actually defined as +(void)setDouble:(float)value forKey:(NSString*)key. The value passed was a double but was converted to a float for use in the method. A simple copy and paste issue. Too bad the Objective-C compiler didn't at least throw up a warning like it seems to do for everything else...

这篇关于Objective-C浮点/双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆