英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论