如何围绕CGFloat [英] How to round CGFloat

查看:109
本文介绍了如何围绕CGFloat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了这个方法

+ (CGFloat) round: (CGFloat)f {
    int a = f;
    CGFloat b = a;
    return b;
}

它按预期工作但它只会向下舍入。如果它是一个负数,它仍然会向下舍入。

It works as expected but it only rounds down. And if it's a negative number it still rounds down.

这只是我做的一个快速方法,它正确地舍入是不是很重要,我只是做了它为我的游戏舍入相机的x和y值。

This was just a quick method I made, it isn't very important that it rounds correctly, I just made it to round the camera's x and y values for my game.

这种方法可以吗?它快吗?或者有更好的解决方案吗?

Is this method okay? Is it fast? Or is there a better solution?

推荐答案

已有标准函数,您可能需要在<中使用的行为; math.h> ,例如: floorf ceilf
roundf rintf nearbyintf (lasf'f'表示浮动版本,没有它的版本是双版本。)

There are already standard functions with behaviors you might need in <math.h> such as: floorf, ceilf, roundf, rintf and nearbyintf (lasf 'f' means "float" version, versions without it are "double" versions).

最好使用标准方法,不仅因为它们是标准的,而且因为它们在边缘工作得更好案例。

It is better to use standard methods not only because they are standard, but because they work better in edge cases.

2013年更新(jessedc)

iOS不再只是32位。这个问题有很多其他答案现在更具相关性。

iOS is no longer only 32 bit. There are a number of other answers to this question that are now more relevant.

大多数答案提到导入 tgmath.h

  • https://stackoverflow.com/a/5352779/184130
  • https://stackoverflow.com/a/7695011/184130

这篇关于如何围绕CGFloat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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