重新映射一个数值从一个范围到另一个范围。

huangapple go评论90阅读模式
英文:

Re-map a number from one range to another

问题

在Go语言中,没有直接等价于Arduino的map函数的功能。但是你可以通过编写自定义函数来实现相似的功能。以下是一个示例实现:

func mapValue(value, fromLow, fromHigh, toLow, toHigh float64) float64 {
    return (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow
}

你可以将需要映射的值、原始范围的最小值和最大值,以及目标范围的最小值和最大值作为参数传递给mapValue函数,它将返回映射后的值。

使用示例:

result := mapValue(50, 0, 100, 0, 255)
fmt.Println(result) // 输出:127.5

在这个示例中,输入的值是50,原始范围是0到100,目标范围是0到255。函数将50从原始范围映射到目标范围,返回的结果是127.5。

希望这可以帮助到你!如果你有任何其他问题,请随时问我。

英文:

Is there any equivalent in go for the Arduino map function?

> map(value, fromLow, fromHigh, toLow, toHigh)
>
> Description
>
> Re-maps a number from one range to another. That is, a value of
> fromLow would get mapped to toLow, a value of fromHigh to toHigh,
> values in-between to values in-between, etc

If not, how would I implement this in go?

答案1

得分: 4

在Go语言中,没有与Arduino的map函数完全等效的函数。标准库中的math没有提供这样的函数。

如果没有,你可以将原始代码翻译成Go语言。C语言和Go语言在语法上非常相似,因此这个任务非常容易。你链接的map函数的手册页面给出了代码。将其翻译成Go语言非常简单。

你可以将原始代码翻译成类似以下的Go语言代码:

func Map(x, in_min, in_max, out_min, out_max int64) int64 {
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
}

这里是一个在Go Playground上的示例

请注意,在Go语言中,map不是一个有效的函数名,因为已经有了map内置类型,使得map成为一个保留关键字,用于定义映射类型,类似于[]T语法。

英文:

> Is there any equivalent in go for the Arduino map function?

The standard library, or more specifically the math package, does not offer such a function, no.

> If not, how would I implement this in go?

By taking the original code and translating it to Go. C and Go are very related syntactically and therefore this task is very, very easy. The manual page for map that you linked gives you the code. A translation to go is, as already mentioned, trivial.

Original from the page you linked:

> For the mathematically inclined, here's the whole function
>
> long map(long x, long in_min, long in_max, long out_min, long out_max)
> {
> return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
> }

You would translate that to something like

func Map(x, in_min, in_max, out_min, out_max int64) int64 {
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
}

Here is an example on the go playground.

Note that map is not a valid function name in Go since there is already the map <del>built-in type which makes map a reserved keyword.</del> keyword for defining map types, similar to the []T syntax.

huangapple
  • 本文由 发表于 2014年9月15日 10:02:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/25839880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定