Objective-C 中的浮动问题

发布于 2024-07-30 06:44:04 字数 336 浏览 2 评论 0原文

我有一个小问题,但找不到解决方案!

我的代码是(这只是示例代码,但我的原始代码做了类似的事情):

float x = [@"2.45" floatValue];


for(int i=0; i<100; i++)
    x += 0.22;

NSLog(@"%f", x);

输出是 52.450001 而不是 52.450000 !

我不知道,因为这发生了!

谢谢你的帮助!

~已解决~

谢谢大家! 是的,我已经用 double 类型解决了!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

染年凉城似染瑾 2024-08-06 06:44:05

浮点数是具有一定精度的数字表示形式。 并非每个值都可以用这种格式表示。 另请参阅此处

你可以很容易地想到为什么会出现这种情况:在区间 (1..1) 中有无限数量的数字,但浮点数只有有限数量的位数来表示 (-MAXFLOAT..1) 中的所有数字。最大浮动)。

更恰当地说:在 32 位整数表示中,有无数个整数需要表示,但有无数个实数值无法在 32 或 64 位的有限表示中完全表示。 因此,不仅可表示的最高和最低实际值受到限制,而且精度也受到限制。

那么为什么浮点后的数字会受到影响呢? 因为表示是基于二进制而不是十进制,所以其他数字比十进制数字更容易表示。

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.

╰◇生如夏花灿烂 2024-08-06 06:44:05

浮点数并不总是可以轻松地由计算机表示。 这会导致某些数字不准确。

这就像我问你 1/3 的十进制是多少。 无论您多么努力,您都无法告诉我它是什么,因为十进制无法准确描述该数字。

浮点数无法准确描述一些小数。

Floating point numbers can not always be represented easily by computers. This leads to inaccuracy in some digits.

It's like me asking you what 1/3 is in decimal. No matter how hard you try, you're not going to be able to tell me what it is because decimal can't accurately describe that number.

Floats can't accurately describe some decimal numbers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文