将浮点取整为预定义点的规则网格 [英] Round a float to a regular grid of predefined points

查看:63
本文介绍了将浮点取整为预定义点的规则网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将浮点数四舍五入到给定的精度,例如:

I want to round a float number to a given precision, for example :

0.051 i want to convert it to
0.1

0.049 i want to convert it to
0.0

0.56 i want to convert it to
0.6

0.54 i want to convert it to
0.5

我无法更好地解释它,但是这样做的原因是将点位置(如0.131f,0.432f)转换为网格中图块的位置(如0.1f,0.4f)。

I cant explain it better, but the reason for this is to translate a point location (like 0.131f, 0.432f) to the location of tile in a grid (like 0.1f, 0.4f).

推荐答案

只要您的网格是规则的,只需查找从整数到此网格的转换即可。假设您的网格为

As long as your grid is regular, just find a transformation from integers to this grid. So let's say your grid is

0.2  0.4  0.6  ...

然后轮到您

float round(float f)
{
    return floor(f * 5 + 0.5) / 5;
    // return std::round(f * 5) / 5; // C++11
}

这篇关于将浮点取整为预定义点的规则网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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