Objective-C:floorf()返回错误值 [英] Objective-C: floorf( ) returns wrong value

查看:79
本文介绍了Objective-C:floorf()返回错误值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

    float passedPrice = 2.953;
    float placed = 1000.0; //3 decimals
    NSLog("%f", placed); // Gives 2953;
    float withNoFractions = floorf(passedPrice * placed);

withNoFractions中存储的值为2952!应该是2953年.真正奇怪的是它可以工作一段时间.

The value stored in withNoFractions is 2952! It shall be 2953. What is really strange is that it works some time.

推荐答案

许多十进制浮点分数不能表示为二进制的精确分数,因此必须将其近似. 2.953被近似为2.95299999.当您乘以1000时,结果为2952.99999,当您获得该值的底数时,结果为2952.

Many decimal floating point fractions cannot be represented as exact fractions in binary, so they have to be approximated. 2.953 is being approximated as something like 2.95299999. When you multiply by 1000, the result is 2952.99999, and when you get the floor of this, it's 2952.

要解决此问题,可以使用round()代替ffloorf(),也可以在调用ffloorf()之前添加0.5:

To solve this, you can either use round() instead of ffloorf(), or you can add 0.5 before calling ffloorf():

float withNoFractions = floorf(passedPrice * placed + 0.5);

这篇关于Objective-C:floorf()返回错误值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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