问题描述
我有一个小问题,我找不到解决方案!
我的代码是(这只是一个示例代码,但我的原始代码做某事像这样):
float x = [@2.45floatValue];
for(int i = 0; i x + = 0.22;
NSLog(@%f,x);
输出为52.450001而不是52.450000!
我不知道,因为这发生!
感谢任何帮助!
〜SOLVED〜 b
$ b
感谢大家!是的,我已经解决了double类型!
浮点数是一个精度的数字表示。不是每个值都可以用这种格式表示。请参见。
你可以很容易想到为什么会是这种情况:在intervall(1..1)中有一个无限数量的数字,有限数量的位表示(-MAXFLOAT..MAXFLOAT)中的所有数字。
更合适的是:在32位整数表示中,有一个可计数的整数表示,但有无限的无数的实数值不能完全表示在32或64位的有限表示。因此,不仅对最高和最低可表示的实际价值有限制,而且对准确性也有限制。
因此,为什么在浮点数后面有一个数字受影响?因为表示是基于二进制系统而不是十进制,所以其他数字很容易表示,而十进制。
I've a small problem and I can't find a solution!
My code is (this is only a sample code, but my original code do something like this):
float x = [@"2.45" floatValue];
for(int i=0; i<100; i++)
x += 0.22;
NSLog(@"%f", x);
the output is 52.450001 and not 52.450000 !
I don't know because this happens!
Thanks for any help!
~SOLVED~
Thanks to everybody! Yes, I've solved with the double type!
Floats are a number representation with a certain precision. Not every value can be represented in this format. See here as well.
You can easily think of why this would be the case: there is an unlimited number of number just in the intervall (1..1), but a float only has a limited number of bits to represent all numbers in (-MAXFLOAT..MAXFLOAT).
More aptly put: in a 32bit integer representation there is a countable number of integers to be represented, But there is an infinite innumerable number of real values that cannot be fully represented in a limited representation of 32 or 64bit. Therefore there not only is a limit to the highest and lowest representable real value, but also to the accuracy.
So why is a number that has little digits after the floating point affected? Because the representation is based on a binary system instead of a decimal, making other numbers easily represented then the decimal ones.
这篇关于在Objective-C中的浮动问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!