使用递归在Go中保持扫描输入。

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

Keep Scanning in Input using Recursion with Go

问题

我正在尝试解决一个问题,要求不使用for/while循环,而是使用递归。问题给出的输入格式如下:

使用递归在Go中保持扫描输入。

其中"2"是查询的数量,每个查询包含一个数字列表的长度,后跟数字。我需要扫描所有的信息,并打印出数字的总和(在这个例子中是3 + -1 + 1 + 14和9 + 6 + -53 + 32 + 16)。我尝试使用递归来扫描数字,但似乎无法正确扫描它们。有什么问题吗?

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	recur(n)
}

func print_sum(l int, sum int) int {
	if l == 0 {
		return sum
	}
	var next_digit int
	fmt.Scan(&next_digit)
	print_sum(l-1, sum+next_digit)
	return 0
}

func recur(queries int) {
	if queries == 0 {
		return
	}
	var next_len int
	fmt.Scan(&next_len)
	print_sum(next_len, 0)
	recur(queries - 1)
}
英文:

I am trying to do a problem without using for/while loops and with recursion. The problem gives you an input in this format:

使用递归在Go中保持扫描输入。

where "2" is the number of queries and each query contains the length of a list of digits followed by the digits. I need to scan in all the information and print out the sum of the digits(in this case 3 + -1 + 1 + 14 and 9 + 6 + -53 + 32 + 16). I am trying to use recursion to scan in the digits, but I can't seem to scan them in properly. Does any

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	recur(n)
}

func print_sum(l int, sum int) int {
	if l == 0 {
		return sum
	}
	var next_digit int
	fmt.Scan(next_digit)
	print_sum(l-1, sum+next_digit)
	return 0
}
func recur(queries int) {
	if queries == 0 {
		return
	}
	var next_len int
	fmt.Scan(next_len)
	print_sum(next_len, 0)
	recur(queries - 1)
}

答案1

得分: 0

我能够找到解决方案,如果有人想查看代码,这是代码的链接:https://github.com/allenye66/Recursive-Sum-of-Squares

英文:

I was able to figure out the solution, here is the code if anyone wants to look at it: https://github.com/allenye66/Recursive-Sum-of-Squares

huangapple
  • 本文由 发表于 2021年9月20日 05:30:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/69247224.html
匿名

发表评论

匿名网友

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

确定