dpvmtdu364462 2018-08-30 14:03
浏览 79

使用Golang中的递归的数组中的平方和

So my friend gave me this task where the sum of squares of positive numbers must be calculated using recursion.
Conditions - The input will be a string with space separated numbers
This is what I've come so far but this shows a runtime error.

Here is the full error https://ideone.com/53oOjN

package main
import(
    'fmt',
    'strings',
    'strconv'
)
var n int = 4
var sum_of_squares int = 0
func sumOfSquares(strArray []string, iterate int) int{
    number, _ := strconv.Atoi(strArray[iterate])
    if number > 0 {
        sum_of_squares += number*number
    }
    if iterate == n {
        return 0 // just to end the recursion
    }
    return sumOfSquares(strArray, iterate+1)
}
func main() {
    str := "1 2 3 4"
    strArray := strings.Fields(str)
    result := sumOfSquares(strArray, 0)
    fmt.Println(sum_of_squares, result)
}
  • 写回答

2条回答 默认 最新

  • douzhang5199 2018-08-30 14:30
    关注

    The rule of thumb in recursion is termination condition. It should exist and it should exist in the right place.

    func sumOfSquares(strArray []string, iterate int) int{
        if iterate >= len(strArray) { 
            return sum_of_squares
        }
        number, _ := strconv.Atoi(strArray[iterate]) //TODO: handle err here
        sum_of_squares += number*number
    
        return sumOfSquares(strArray, iterate+1)
    }
    

    Just for you information: canonical recursion should not save it's state into global fields. I would suggest using following function signature.

    func sumOfSquares(strArray []string, iterate, currentSum int) int{
        //...    
        return sumOfSquares(strArray, iterate+1, sum_of_squares)
    }
    

    So that you don't need to store sum_of_squares somewhere. You will just pass it to next function invocation.

    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程