如何使用 golang 添加增量数组值

如何在golang中从上到下添加以下数组

例子 :

输入:

[3, 8, 1]

[3, 2, 5]

输出:

[6, 0, 7]

输入:

[7, 6, 7]

[2, 5, 6]

输出:

[9, 1, 4, 1]

这是我的代码:

func main() {

    size := 3

    elements := make([]int, size)

    for i := 0; i < 3; i++ {

        fmt.Scanln(&elements[i])

    }

    fmt.Println("2,5,7", elements)

    result := 0

    for i := 0; i < size; i++ {

        result += elements[i]

    }

    fmt.Println("Sum of elements of array:", result)

}


慕雪6442864
浏览 82回答 1
1回答

慕无忌1623718

从你的问题的输入和输出样本来看,你似乎需要为两个输入数组取 3 个元素并将它们相加。很难通过代码片段来理解你想要实现的目标......但是假设你只关心那些输入和输出样本,那么这就是你可以做的package mainimport "fmt"func main() {&nbsp; size := 3&nbsp; elements1 := make([]int, size)&nbsp; elements2 := make([]int, size)&nbsp; //take elements for the first input array elements1&nbsp; for i := 0; i < size; i++ {&nbsp; &nbsp; fmt.Scanln(&elements1[i])&nbsp; }&nbsp; //take elements for the second input array elements2&nbsp; for i := 0; i < size; i++ {&nbsp; &nbsp; fmt.Scanln(&elements2[i])&nbsp; }&nbsp; //output stores our output array&nbsp; output := []int{}&nbsp; //this store the value to add to the next index eg. 20 + 10 takes 3&nbsp; pushToNextIndex := 0&nbsp; for i, v := range elements1 {&nbsp; &nbsp; sum := v + elements2[i] + pushToNextIndex&nbsp; &nbsp; pushToNextIndex = 0&nbsp; &nbsp; if sum >= 10 {&nbsp; &nbsp; &nbsp; &nbsp; output = append(output, sum%10)&nbsp; &nbsp; &nbsp; &nbsp; pushToNextIndex = sum / 10&nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; }&nbsp; &nbsp; output = append(output, sum)&nbsp; }&nbsp;//if there is still value after iterating all values then append this as the&nbsp;&nbsp;// new array element&nbsp; if pushToNextIndex > 0 {&nbsp; &nbsp; output = append(output, pushToNextIndex)&nbsp; }&nbsp; fmt.Println(output)&nbsp;}请 lemmy 知道这是否不是您要找的!
打开App,查看更多内容
随时随地看视频慕课网APP