在Go语言中,使用递归从一行中扫描数字。

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

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 &quot;fmt&quot;

var a []int

func read(b int) {
	if b == 0 {
		return
	}
	var i int
	_, err := fmt.Scanf(&quot;%d&quot;, &amp;i)
	if err != nil {
		return
	}
	a = append(a, i)
	read(b - 1)
}

func main() {
	read(4)
	fmt.Println(a)
}

Input:

1 15 16 17&lt;Enter&gt;

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 &quot;fmt&quot;

func main() {
	var array []int
	var i int
	for {
		_, err := fmt.Scan(&amp;i)
		if err != nil {
			break
		}
		array = append(array, i)
		fmt.Println(&quot;read number&quot;, i, &quot;from stdin, array &quot;, array)
	}
}

huangapple
  • 本文由 发表于 2016年3月14日 06:39:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/35976781.html
匿名

发表评论

匿名网友

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

确定