dpxnrx11199 2018-12-07 01:24
浏览 45
已采纳

函数返回返回语句时不会退出

I have a strange problem. I was playing with Go and found some very strange behaviour that I couldn't figure it out.

When I run the findMatchingSum function, it searches the expected sum by if sum is bigger I decrement the last index by 1, if bigger, increment the first index by one.

However, when I debug the code, it hits first if statement and should return true, however instead it directly goes and runs last else if statement.

The confusion starts here. On the 3rd iteration it hits the if statement goes into that block but does not quit the function.

Here is the code;

package main

import "fmt"

var arr  = []int{1,2,4,4}

func main() {
    s := findMatchingSum(arr, 8, len(arr) - 1, 0)
    fmt.Println(s)
}

func findMatchingSum(arr []int, sum , last, first int ) bool {
    if arr[first] + arr[last] == sum {
        return true
    } else if  arr[first] + arr[last] > sum {
        findMatchingSum(arr, sum, last - 1, first)
    } else if arr[first] + arr[last] < sum {
        findMatchingSum(arr, sum, last, first + 1)
    }
    return false
}
  • 写回答

1条回答 默认 最新

  • duanma8207 2018-12-07 01:30
    关注

    You forgot to "return" from the else-if branches. This should work:

    func findMatchingSum(arr []int, sum , last, first int ) bool {
        if arr[first] + arr[last] == sum {
            return true
        } else if  arr[first] + arr[last] > sum {
            return findMatchingSum(arr, sum, last - 1, first)
        } else if arr[first] + arr[last] < sum {
            return findMatchingSum(arr, sum, last, first + 1)
        }
        return false
    }
    

    If you don't do this, the third branch will be executed, but the function won't exit - it will jump to the next instruction, which is "return false".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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