Golang: 1 到 100 映射到 2 到 255 的代码实现
在 Golang 中,可以使用以下代码将 1 到 100 映射到 2 到 255:
func mapRange(fromMin, fromMax, toMin, toMax, value int) int {
// 计算输入值在输入范围内的百分比
percentage := float64(value-fromMin) / float64(fromMax-fromMin)
// 根据百分比计算输出范围内的值
mappedValue := int(float64(toMin) + percentage*float64(toMax-toMin))
return mappedValue
}
func main() {
fromMin := 1
fromMax := 100
toMin := 2
toMax := 255
for i := fromMin; i <= fromMax; i++ {
mappedValue := mapRange(fromMin, fromMax, toMin, toMax, i)
fmt.Printf('%d -> %d
', i, mappedValue)
}
}
上述代码中的 mapRange 函数接受输入范围的最小值 fromMin、最大值 fromMax,以及输出范围的最小值 toMin、最大值 toMax,以及要映射的值 value。它首先计算输入值在输入范围内的百分比,然后根据百分比计算输出范围内的值。在 main 函数中,我们使用循环将 1 到 100 的每个值映射到 2 到 255 的范围,并打印映射后的值。
原文地址: http://www.cveoy.top/t/topic/f4kN 著作权归作者所有。请勿转载和采集!