在我寫的類中發現問題,我發現19.8851過去到%f,只能得到19.88509,這是因爲float不能保存太多分數部分?當函數的過去時的浮點值再次不相同
//
// main.m
// 0.6 the_float_not_corrert
//
// Created by Sen on 7/4/14.
// Copyright (c) 2014 SLboat. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* for get a float value from function
*
* @return a flaot value
*/
float getafloat(){
return 19.8851;
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSLog(@"const 19.8851 is %f",19.8851);
NSLog(@"19.8851 is %f",getafloat());
float byValue = 19.8851;
NSLog(@"19.8851 pass in value is %f",byValue);
}
return 0;
}
這是我得到
2014-07-04 09:42:07.508 0.6 the_float_not_corrert[11540:303] const 19.8851 is 19.885100
2014-07-04 09:42:07.510 0.6 the_float_not_corrert[11540:303] 19.8851 is 19.885099
2014-07-04 09:42:07.511 0.6 the_float_not_corrert[11540:303] 19.8851 pass in value is 19.885099
Program ended with exit code: 0
聽起來像float精度問題,因爲是在浮法只有一個精度至7張十進制數。更多信息:http://stackoverflow.com/a/16359692/1301654 – Will
除特殊情況外,浮點數不準確。 –
(第一行更精確,因爲字面值是雙精度值,而不是浮點數。) –