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

huangapple go评论76阅读模式
英文:

How to find sum of integers using recursion(without loops) in Golang?

问题

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

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

输入输入的数量 // 输出
2 // 输入
输入数字的数量 // 输出
2 // 输入
输入数字 // 输出
1 2 // 输入(第二个答案)
输入数字的数量 // 输出
2 // 输入
输入数字
2 3 // 输入(第一个答案)
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(`输入输入的数量`)
	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(`输入数字的数量`)
	_, _ = reader.ReadString('\n')
	fmt.Println(`输入数字`)
	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
	}
}
英文:

Program should ask values "number of numbers" and "numbers" for each "number of inputs", answers are sum of squares of these numbers. My code works but it shows answers in wrong order, how to make it work properly? Outputs should be shown after all inputs.

I think its easier to understand this program by reading inputs and outputs:

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

MyCode:

package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;strconv&quot;
	&quot;strings&quot;
)

func main() {
	reader := bufio.NewReader(os.Stdin) 
	fmt.Println(`Enter the number of inputs`)
	n, _ := reader.ReadString(&#39;\n&#39;) 
	n = strings.TrimRight(n, &quot;\r\n&quot;) 
	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(&#39;\n&#39;) 
	fmt.Println(`Enter the numbers`) 
	input, _ := reader.ReadString(&#39;\n&#39;) 
	input = strings.TrimRight(input, &quot;\r\n&quot;) 
	arr := strings.Split(input, &quot; &quot;) 

	test_cases -= 1

	if test_cases != 0 {
		process_test_case(test_cases, reader)
	}
	fmt.Println(&quot;ans = &quot;, process_array(arr, 0))
	
}

func process_array(arr []string, result int) int {
	num, _ := strconv.Atoi(arr[0]) 
	if len(arr) &gt; 1 {
		next := arr[1:] 
		if num &lt; 0 {
			num = 0
		}
		result = num*num + process_array(next, result)
		return result
	} else {
		if num &gt;= 0 {
			return num * num
		}
		return 0
	}
}

答案1

得分: 0

我已经为您的场景创建了一个示例代码。您可以使用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的评论,您可以更改顺序。返回切片并从末尾打印它。

英文:

I have created a sample code for your scenario. You can modify it by using 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(&quot;num :&quot;, num)

		res += num * num
	}
	return res
}

func process_test_case() int {
	fmt.Println(`Enter the number of numbers`)
	num := 2
	fmt.Println(&quot;number of numbers :&quot;, num)

	fmt.Println(`Enter the numbers`)
	input := &quot;1 2&quot;
	fmt.Println(&quot;the numbers :&quot;, input)
	arr := strings.Split(input, &quot; &quot;)
	res := process_array(arr)
	return res
}

func main() {
	fmt.Println(`Enter the number of inputs`)
	test_cases := 1
	fmt.Println(&quot;number of inputs :&quot;, test_cases)

	for test_cases &gt;= 1 {
		res := process_test_case()
		fmt.Println(res)
		test_cases -= 1
	}

}

You can run it here : https://go.dev/play/p/zGkAln2ghZp

OR

As commented by @phonaputer you can change the sequence. Return the slice and print it from the end.

答案2

得分: 0

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

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)
}

这段代码计算了给定参数列表中的值的总和,并将结果打印出来。函数SumValues使用可变参数y ...int来接收任意数量的整数参数。它通过递归调用自身来计算总和。在每次递归调用中,它将索引x递增,并将当前索引对应的值加到总和中。最后,它返回计算得到的总和。在main函数中,我们调用SumValues函数并将参数0,1,2,3,4,5传递给它,然后将结果打印出来。

英文:

I think this code answer your title of the question:

package main

import &quot;fmt&quot;

func SumValues(x int, y ...int) (sum int) {
	q := len(y) - 1
	sum = y[q - x]
	if x &lt; q {
		sum += SumValues(x + 1, y...)
	}
	return sum
}

func main() {
	sum := SumValues(0,1,2,3,4,5)
	fmt.Println(&quot;Sum is:&quot;, sum)
}

答案3

得分: 0

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

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

以下是Go语言中的递归解决方案:

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()
}

你可以运行这个程序并按照提示输入数字来得到结果。

英文:

> How to find sum of integers using recursion (without loops) in Go?

> The program should ask "number of numbers" and "numbers" for each "number of inputs", answers are sum of squares of these numbers.


Here is an answer to the question, a recursive solution in 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 (
&quot;bufio&quot;
&quot;fmt&quot;
&quot;os&quot;
&quot;strconv&quot;
&quot;strings&quot;
)
func readInt(r *bufio.Reader) int {
line, err := r.ReadString(&#39;\n&#39;)
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(&quot;\nEnter the number of numbers: &quot;)
i := readInt(r)
fmt.Println(&quot;Enter the numbers: &quot;)
*sums = append(*sums, nSquares(i, r))
return nNumbers(n-1, r, sums)
}
func nInputs(r *bufio.Reader) []int {
fmt.Println(&quot;Enter the number of inputs: &quot;)
i := readInt(r)
sums := make([]int, 0, i)
nNumbers(i, r, &amp;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(&quot;\nSum of Squares:&quot;)
sumSqrs(sums)
fmt.Println()
}

huangapple
  • 本文由 发表于 2022年1月5日 12:16:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/70587740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定