为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Golang 中使用递归(无循环)找到整数的总和?

如何在 Golang 中使用递归(无循环)找到整数的总和?

Go
POPMUISE 2022-10-24 15:06:48
程序应该询问每个“输入数”的值“数字”和“数字”,答案是这些数字的平方和。我的代码有效,但它以错误的顺序显示答案,如何使其正常工作?应在所有输入之后显示输出。我认为通过阅读输入和输出更容易理解这个程序:Enter the number of inputs // output2 // inputEnter the number of numbers // output2 // inputEnter the numbers // output 1 2 // input (second ans)Enter the number of numbers // output 2 // inputEnter the numbers 2 3 // input (first ans)ans =  13 // ans = 2^2 + 3^2ans =  5 () // ans = 1^2 + 2^2我的代码:package mainimport (    "bufio"    "fmt"    "os"    "strconv"    "strings")func main() {    reader := bufio.NewReader(os.Stdin)     fmt.Println(`Enter the number of inputs`)    n, _ := reader.ReadString('\n')     n = strings.TrimRight(n, "\r\n")     test_cases, err := strconv.Atoi(n)     if err != nil {        fmt.Println(err)    }    process_test_case(test_cases, reader)}func process_test_case(test_cases int, reader *bufio.Reader) {    fmt.Println(`Enter the number of numbers`)     _, _ = reader.ReadString('\n')     fmt.Println(`Enter the numbers`)     input, _ := reader.ReadString('\n')     input = strings.TrimRight(input, "\r\n")     arr := strings.Split(input, " ")     test_cases -= 1    if test_cases != 0 {        process_test_case(test_cases, reader)    }    fmt.Println("ans = ", process_array(arr, 0))    }func process_array(arr []string, result int) int {    num, _ := strconv.Atoi(arr[0])     if len(arr) > 1 {        next := arr[1:]         if num < 0 {            num = 0        }        result = num*num + process_array(next, result)        return result    } else {        if num >= 0 {            return num * num        }        return 0    }}
查看完整描述

3 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

如何在 Go 中使用递归(无循环)找到整数的总和?


程序应该询问每个“输入数量”的“数字数量”和“数字”,答案是这些数字的平方和。


这是问题的答案,Go 中的递归解决方案:


$ go run sumsq.go


Enter the number of inputs:

2


Enter the number of numbers:

2

Enter the numbers:

1

2


Enter the number of numbers:

2

Enter the numbers:

2

3


Sum of Squares:

5

13


package main


import (

    "bufio"

    "fmt"

    "os"

    "strconv"

    "strings"

)


func readInt(r *bufio.Reader) int {

    line, err := r.ReadString('\n')

    line = strings.TrimSpace(line)

    if err != nil {

        if len(line) == 0 {

            return 0

        }

    }

    i, err := strconv.Atoi(line)

    if err != nil {

        return 0

    }

    return i

}


func nSquares(n int, r *bufio.Reader) int {

    if n == 0 {

        return 0

    }

    i := readInt(r)

    return i*i + nSquares(n-1, r)

}


func nNumbers(n int, r *bufio.Reader, sums *[]int) int {

    if n == 0 {

        return 0

    }

    fmt.Println("\nEnter the number of numbers: ")

    i := readInt(r)


    fmt.Println("Enter the numbers: ")

    *sums = append(*sums, nSquares(i, r))

    return nNumbers(n-1, r, sums)

}


func nInputs(r *bufio.Reader) []int {

    fmt.Println("Enter the number of inputs: ")

    i := readInt(r)

    sums := make([]int, 0, i)

    nNumbers(i, r, &sums)

    return sums

}


func sumSqrs(sums []int) {

    if len(sums) == 0 {

        return

    }

    fmt.Println(sums[0])

    sumSqrs(sums[1:])

}


func main() {

    r := bufio.NewReader(os.Stdin)

    fmt.Println()

    sums := nInputs(r)

    fmt.Println("\nSum of Squares:")

    sumSqrs(sums)

    fmt.Println()

}


查看完整回答
反对 回复 2022-10-24
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

我为您的场景创建了一个示例代码。您可以使用修改它bufio.NewReader(os.Stdin)


func process_array(arr []string) int {


    res := 0

    for _, v := range arr {

        num, err := strconv.Atoi(v)

        if err != nil {

            panic(err)

        }

        fmt.Println("num :", num)


        res += num * num

    }

    return res

}


func process_test_case() int {

    fmt.Println(`Enter the number of numbers`)

    num := 2

    fmt.Println("number of numbers :", num)


    fmt.Println(`Enter the numbers`)

    input := "1 2"

    fmt.Println("the numbers :", input)

    arr := strings.Split(input, " ")

    res := process_array(arr)

    return res

}


func main() {

    fmt.Println(`Enter the number of inputs`)

    test_cases := 1

    fmt.Println("number of inputs :", test_cases)


    for test_cases >= 1 {

        res := process_test_case()

        fmt.Println(res)

        test_cases -= 1

    }


}

你可以在这里运行它:https ://go.dev/play/p/zGkAln2ghZp


或者


正如@phonaputer 评论的那样,您可以更改顺序。返回切片并从末尾打印。


查看完整回答
反对 回复 2022-10-24
?
呼唤远方

TA贡献1856条经验 获得超11个赞

我认为这段代码回答了您的问题标题:


package main


import "fmt"


func SumValues(x int, y ...int) (sum int) {

    q := len(y) - 1

    sum = y[q - x]

    if x < q {

        sum += SumValues(x + 1, y...)

    }

    return sum

}


func main() {

    sum := SumValues(0,1,2,3,4,5)

    fmt.Println("Sum is:", sum)

}


查看完整回答
反对 回复 2022-10-24
  • 3 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号