这是我的代码:
type Cake struct {
weight int
value int
costBenefit float32
}
func (c *Cake) SetCostBenefit() float32 {
if c.costBenefit == 0 {
c.costBenefit = float32(c.value) / float32(c.weight)
}
return c.costBenefit
}
func main() {
capacity := 20
cakes := []Cake{{weight: 7, value: 160}, {weight: 3, value: 90}, {weight: 2, value: 15}}
result := maxDuffelBagValue(cakes, capacity)
fmt.Printf("Max capacity %d", result)
}
func maxDuffelBagValue(cakes []Cake, capacity int) int {
calcCostBenefit(&cakes)
for _, c := range cakes {
fmt.Printf("Value Cake cost benefit 2: %v \n", c.costBenefit)
}
return 0
}
func calcCostBenefit(cakes *[]Cake) {
for _, c := range *cakes {
c.SetCostBenefit()
fmt.Printf("Value Cake cost benefit 1: %v \n", c.costBenefit)
}
}
正如您在上面看到的,我有一个结构方法,用于设置结构蛋糕的 CostBenefit 属性。由于我将蛋糕数组发送到方法calcCostBenefit,因此方法中的任何更改都应反映外部的数组(调用方方法)。但实际上,这并没有发生。下面是输出:
Value Cake cost benefit 1: 22.857143
Value Cake cost benefit 1: 30
Value Cake cost benefit 1: 7.5
Value Cake cost benefit 2: 0
Value Cake cost benefit 2: 0
Value Cake cost benefit 2: 0
值重置为零,我不知道为什么。我尝试了代码中的一些更改,但没有任何效果。我在这里错过了什么?这让我发疯,没有任何东西能够发现可能如此明显和简单的东西。
森栏
相关分类