15

C#中是否有像Arduino的地图这样的功能?

4

2 回答 2

22

您可以使用扩展方法decimal例如)来做到这一点:

public static class ExtensionMethods
{
    public static decimal Map (this decimal value, decimal fromSource, decimal toSource, decimal fromTarget, decimal toTarget)
    {
        return (value - fromSource) / (toSource - fromSource) * (toTarget - fromTarget) + fromTarget;
    }
}

然后你可以像这样使用它:

decimal res = 2.Map(1, 3, 0, 10);
// res will be 5
于 2013-01-16T07:50:32.177 回答
4
private static int map(int value, int fromLow, int fromHigh, int toLow, int toHigh) 
{
    return (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
}
于 2019-06-19T10:30:29.437 回答