猿问

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

程序应该询问每个“输入数”的值“数字”和“数字”,答案是这些数字的平方和。我的代码有效,但它以错误的顺序显示答案,如何使其正常工作?应在所有输入之后显示输出。


我认为通过阅读输入和输出更容易理解这个程序:


Enter the number of inputs // output

2 // input

Enter the number of numbers // output

2 // input

Enter the numbers // output 

1 2 // input (second ans)

Enter the number of numbers // output 

2 // input

Enter the numbers 

2 3 // input (first ans)

ans =  13 // ans = 2^2 + 3^2

ans =  5 () // ans = 1^2 + 2^2

我的代码:


package main


import (

    "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

    }

}


POPMUISE
浏览 94回答 3
微课
3回答

猛跑小猪

如何在 Go 中使用递归(无循环)找到整数的总和?程序应该询问每个“输入数量”的“数字数量”和“数字”,答案是这些数字的平方和。这是问题的答案,Go 中的递归解决方案:$ go run sumsq.goEnter the number of inputs:2Enter the number of numbers:2Enter the numbers:12Enter the number of numbers:2Enter the numbers:23Sum of Squares:513$&nbsp;package mainimport (&nbsp; &nbsp; "bufio"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os"&nbsp; &nbsp; "strconv"&nbsp; &nbsp; "strings")func readInt(r *bufio.Reader) int {&nbsp; &nbsp; line, err := r.ReadString('\n')&nbsp; &nbsp; line = strings.TrimSpace(line)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; if len(line) == 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; i, err := strconv.Atoi(line)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; }&nbsp; &nbsp; return i}func nSquares(n int, r *bufio.Reader) int {&nbsp; &nbsp; if n == 0 {&nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; }&nbsp; &nbsp; i := readInt(r)&nbsp; &nbsp; return i*i + nSquares(n-1, r)}func nNumbers(n int, r *bufio.Reader, sums *[]int) int {&nbsp; &nbsp; if n == 0 {&nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("\nEnter the number of numbers: ")&nbsp; &nbsp; i := readInt(r)&nbsp; &nbsp; fmt.Println("Enter the numbers: ")&nbsp; &nbsp; *sums = append(*sums, nSquares(i, r))&nbsp; &nbsp; return nNumbers(n-1, r, sums)}func nInputs(r *bufio.Reader) []int {&nbsp; &nbsp; fmt.Println("Enter the number of inputs: ")&nbsp; &nbsp; i := readInt(r)&nbsp; &nbsp; sums := make([]int, 0, i)&nbsp; &nbsp; nNumbers(i, r, &sums)&nbsp; &nbsp; return sums}func sumSqrs(sums []int) {&nbsp; &nbsp; if len(sums) == 0 {&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(sums[0])&nbsp; &nbsp; sumSqrs(sums[1:])}func main() {&nbsp; &nbsp; r := bufio.NewReader(os.Stdin)&nbsp; &nbsp; fmt.Println()&nbsp; &nbsp; sums := nInputs(r)&nbsp; &nbsp; fmt.Println("\nSum of Squares:")&nbsp; &nbsp; sumSqrs(sums)&nbsp; &nbsp; fmt.Println()}

人到中年有点甜

我为您的场景创建了一个示例代码。您可以使用修改它bufio.NewReader(os.Stdin)func process_array(arr []string) int {&nbsp; &nbsp; res := 0&nbsp; &nbsp; for _, v := range arr {&nbsp; &nbsp; &nbsp; &nbsp; num, err := strconv.Atoi(v)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("num :", num)&nbsp; &nbsp; &nbsp; &nbsp; res += num * num&nbsp; &nbsp; }&nbsp; &nbsp; return res}func process_test_case() int {&nbsp; &nbsp; fmt.Println(`Enter the number of numbers`)&nbsp; &nbsp; num := 2&nbsp; &nbsp; fmt.Println("number of numbers :", num)&nbsp; &nbsp; fmt.Println(`Enter the numbers`)&nbsp; &nbsp; input := "1 2"&nbsp; &nbsp; fmt.Println("the numbers :", input)&nbsp; &nbsp; arr := strings.Split(input, " ")&nbsp; &nbsp; res := process_array(arr)&nbsp; &nbsp; return res}func main() {&nbsp; &nbsp; fmt.Println(`Enter the number of inputs`)&nbsp; &nbsp; test_cases := 1&nbsp; &nbsp; fmt.Println("number of inputs :", test_cases)&nbsp; &nbsp; for test_cases >= 1 {&nbsp; &nbsp; &nbsp; &nbsp; res := process_test_case()&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(res)&nbsp; &nbsp; &nbsp; &nbsp; test_cases -= 1&nbsp; &nbsp; }}你可以在这里运行它:https ://go.dev/play/p/zGkAln2ghZp或者正如@phonaputer 评论的那样,您可以更改顺序。返回切片并从末尾打印。

呼唤远方

我认为这段代码回答了您的问题标题:package mainimport "fmt"func SumValues(x int, y ...int) (sum int) {&nbsp; &nbsp; q := len(y) - 1&nbsp; &nbsp; sum = y[q - x]&nbsp; &nbsp; if x < q {&nbsp; &nbsp; &nbsp; &nbsp; sum += SumValues(x + 1, y...)&nbsp; &nbsp; }&nbsp; &nbsp; return sum}func main() {&nbsp; &nbsp; sum := SumValues(0,1,2,3,4,5)&nbsp; &nbsp; fmt.Println("Sum is:", sum)}
随时随地看视频慕课网APP

相关分类

Go
我要回答