问题描述
我有一个小问题,我找不到解决方案!
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);
输出是 52.450001 而不是 52.450000!
the output is 52.450001 and not 52.450000 !
我不知道,因为这种情况发生了!
I don't know because this happens!
感谢您的帮助!
~解决~
谢谢大家!是的,我已经用 double 类型解决了!
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.
你可以很容易地想到为什么会这样:在区间 (1..1) 中有无限数量的数字,但浮点数只有有限数量的位来表示 (-MAXFLOAT..MAXFLOAT).
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).
更恰当地说:在 32 位整数表示中,有可数数量的整数要表示,但是在 32 位或 64 位的有限表示中无法完全表示无限数量的实数值.因此,不仅对可表示的最高和最低实值有限制,而且对准确率也有限制.
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 中的浮点数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!