如何安全地将CGFloat地板或吊顶到int? [英] How to safely floor or ceil a CGFloat to int?

查看:152
本文介绍了如何安全地将CGFloat地板或吊顶到int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了计算数组索引,我经常需要将CGFloat放到顶部或悬吊到int上.

I often need to floor or ceil a CGFloat to an int, for calculation of an array index.

我经常在floorf(theCGFloat)ceilf(theCGFloat)上看到的问题是浮点错误可能会带来麻烦.

The problem I permanently see with floorf(theCGFloat) or ceilf(theCGFloat) is that there can be troubles with floating point inaccuracies.

所以如果我的CGFloat2.0f,但是在内部将其表示为1.999999999999f或类似的东西怎么办.我执行floorf并得到1.0f,它又是一个浮点数.但是我必须将此野兽强制转换为int,这可能会带来另一个问题.

So what if my CGFloat is 2.0f but internally it is represented as 1.999999999999f or something like that. I do floorf and get 1.0f, which is a float again. And yet I must cast this beast to int which may introduce another problem.

是否有最佳实践,如何将float铺平或吊装到int,以使诸如2.0的铺装永远不会意外地铺平到1,而诸如2.0的铺装永远不会意外地铺平到int 2?

Is there a best practice how to floor or ceil a float to an int such that something like 2.0 would never accidentally get floored to 1 and something like 2.0 would never accidentally get ceiled to 2?

推荐答案

您的问题中存在一些误解.

There are a couple misconceptions in your question.

如果我的CGFloat为2.0f,但内部将其表示为1.999999999999f,该怎么办

what if my CGFloat is 2.0f but internally it is represented as 1.999999999999f

不可能发生;像所有合理的小整数一样,2.0在浮点数中具有精确的表示形式.如果您的CGFloat2.0f,则实际上是2.0.

can't happen; 2.0, like all reasonably small integers, has an exact representation in floating-point. If your CGFloat is 2.0f, then it really is 2.0.

2.0之类的东西永远都不会被顶到2

something like 2.0 would never accidentally get ceiled to 2

2.0 的上限是 2;还会是什么?

The ceiling of 2.0 is 2; what else would it possibly be?

我认为您真正要问的问题是假设我进行的计算会产生不精确的结果,在数学上应该的精确度应为2.0,但实际上略小;当我应用floor达到该值,我得到的是1.0而不是2.0-如何防止这种情况发生?"

I think the question that you're really asking is "suppose I do a calculation that produces an inexact result, which mathematically should be exactly 2.0, but is actually slightly less; when I apply floor to that value, I get 1.0 instead of 2.0--how do I prevent this?"

这实际上是一个相当微妙的问题,没有一个正确"的答案.您如何计算输入值?您将如何处理结果?

That's actually a fairly subtle question that doesn't have a single "right" answer. How have you computed the input value? What are you going to do with the result?

这篇关于如何安全地将CGFloat地板或吊顶到int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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