如何像在Arduino中映射一样在C#中映射数字? [英] How do I map numbers in C# like with map in Arduino?

查看:71
本文介绍了如何像在Arduino中映射一样在C#中映射数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中是否有像Arduino的 map 之类的功能?

Is there a function like Arduino's map in C#?

推荐答案

您可以使用扩展方法(例如,十进制):

You can do it with an Extension Method (for decimal for example):

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;
    }
}

然后您可以像使用它一样

Then you can use it like:

decimal res = 2.Map(1, 3, 0, 10);
// res will be 5

这篇关于如何像在Arduino中映射一样在C#中映射数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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