英文:
In Go, scan numbers from a line using recursion
问题
我想将一行整数从标准输入扫描到一个整数切片中。每个整数之间用空格分隔。用户输入的整数数量可能有N个。我试图不使用for循环来实现。例如,
1 15 16 17
到目前为止,这是我执行任务的函数:
var array []int
func read(b int) {
if b == 0 {
return
}
fmt.Scanf("%d", &array)
read(b - 1)
}
这个函数的思路是从输入中读取"1 15 16 17",并将其转换为值为[1 15 16 17]的切片。
编译后,我得到了错误:
运行时错误
英文:
I want to scan a line of integers from stdin into a slice of integers. Each integer is separated by whitespace. Ther would be as many as N integers of user input. I'm trying not to use a for loop. For example,
1 15 16 17
So far, this is my function to perform the task,
var array []int
func read(b int) {
if b == 0 {
return
}
fmt.Scanf("%d", &array)
read(b - 1)
}
The idea is to read from the input, 1 15 16 17, and make it into a slice with value [1 15 16 17]
After compiling, I got the error,
Runtime error
答案1
得分: 0
例如,
package main
import "fmt"
var a []int
func read(b int) {
if b == 0 {
return
}
var i int
_, err := fmt.Scanf("%d", &i)
if err != nil {
return
}
a = append(a, i)
read(b - 1)
}
func main() {
read(4)
fmt.Println(a)
}
输入:
1 15 16 17<Enter>
输出:
[1 15 16 17]
英文:
For example,
package main
import "fmt"
var a []int
func read(b int) {
if b == 0 {
return
}
var i int
_, err := fmt.Scanf("%d", &i)
if err != nil {
return
}
a = append(a, i)
read(b - 1)
}
func main() {
read(4)
fmt.Println(a)
}
Input:
1 15 16 17<Enter>
Output:
[1 15 16 17]
答案2
得分: -1
不是递归的,而是读取整数直到stdin关闭或读取到无法转换为整数的内容。
package main
import "fmt"
func main() {
var array []int
var i int
for {
_, err := fmt.Scan(&i)
if err != nil {
break
}
array = append(array, i)
fmt.Println("从stdin读取数字", i, ",数组为", array)
}
}
英文:
Not recursive, but just reading integers until stdin is closed or something that can't be converted to an integer is read.
package main
import "fmt"
func main() {
var array []int
var i int
for {
_, err := fmt.Scan(&i)
if err != nil {
break
}
array = append(array, i)
fmt.Println("read number", i, "from stdin, array ", array)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论