dongzong2017 2018-08-02 14:54
浏览 37

在Go中使用递归练习“裸体回报”。 ELSE语句中的return语句不正确吗?

Trying a simple recursive function that takes a number, splits it in a certain way, and is only supposed to return it if the split numbers are equal to each other.

package main

import "fmt"

func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x

    if y == x || sum > 200 {
        return
    } else {
        split(sum+1)
        return
    }
}

func main() {
    fmt.Println(split(10))
}

The output for fmt.Println(split(10)) is 4 and 6, which is incorrect since they're not equal to each other. Is this due to the return statement t the end of my ELSE statement? I have a JAVA background so I figured that line would never get hit.

  • 写回答

1条回答 默认 最新

  • doushenxu7294 2018-08-02 17:56
    关注

    As you are declaring the variables in the function definition with (x, y int) performing a return will return the values of x and y at that point. When you call the split function recursively it will assign a new x and y for that function call, so changing the values there will not effect the outer scope.

    You can fix this by returning the return value of the recursive split call, as currently you are ignoring the results by calling it on the line before the return.

    However I would note that any input value > 0 will never be equal in this implementation and will return the same value for any input as the sum > 200 clause triggers.

    https://play.golang.org/p/fzuPtqPCxpE

    package main
    
    import "fmt"
    
    func split(sum int) (int, int) {
        x := sum * 4 / 9
        y := sum - x
    
        if y == x || sum > 200 {
            return
        } else {
            return split(sum + 1)
        }
    }
    
    func main() {
        fmt.Println(split(10))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度