英文:
Keep Scanning in Input using Recursion with Go
问题
我正在尝试解决一个问题,要求不使用for/while循环,而是使用递归。问题给出的输入格式如下:
其中"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:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论