我在操场上有这个代码。我使用排序从切片/数组中获取最大值和最小值。当我需要以x个周期的间隔获取值时,问题就开始了。如果你运行代码,你将在最后一次打印有一个值1.0407,但是x周期之前不再有这个值,这个值离x的周期很远。所以我的问题是,他为什么偷看这个值?而min没有。
package main
import (
"fmt"
"math"
"sort"
)
func main() {
var period = 5
var highest float64
var lowest float64
for i, v := range x {
if i < period {
continue
}
var correctHighest, correctLowest = MaxMin(x[i-period : i])
fmt.Println("Correct -", "Price:", v, "Highest:", correctHighest, "Lowest:", correctLowest)
}
for i, v := range x {
if i < period {
continue
}
var correctHighest, correctLowest = MaxMin(x[i-period : i])
fmt.Println("Correct -", "Highest:", correctHighest, "Lowest:", correctLowest)
highest = Max(x[i-period : i]...)
lowest = Min(x[i-period : i]...)
fmt.Println("Price:", v, "Highest:", highest, "Lowest:", lowest)
}
}
// Both does not work
func Max(n ...float64) float64 {
sort.Float64s(n)
if len(n) == 0 {
return 0.
}
return n[len(n)-1]
}
func Min(n ...float64) float64 {
sort.Float64s(n)
if len(n) == 0 {
return 0.
}
return n[0]
}
// New code that works
func MaxMin(n []float64) (float64, float64) {
if len(n) == 0 {
return 0., 0.
}
var max float64
var min = math.MaxFloat64
for _, value := range n {
if value > max {
max = value
}
if value < min {
min = value
}
}
return max, min
}
去
一只萌萌小番薯
相关分类