如何使用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)
}

从你的问题的输入和输出样本,似乎你需要采取3个元素为两个输入数组,并将它们加在一起。通过跟踪代码片段,很难理解你想要实现什么……但是,假设您只关心这些输入和输出样本,那么您可以这样做

package main
import "fmt"
func main() {
size := 3
elements1 := make([]int, size)
elements2 := make([]int, size)
//take elements for the first input array elements1
for i := 0; i < size; i++ {
fmt.Scanln(&elements1[i])
}
//take elements for the second input array elements2
for i := 0; i < size; i++ {
fmt.Scanln(&elements2[i])
}
//output stores our output array
output := []int{}
//this store the value to add to the next index eg. 20 + 10 takes 3
pushToNextIndex := 0
for i, v := range elements1 {
sum := v + elements2[i] + pushToNextIndex
pushToNextIndex = 0
if sum >= 10 {
output = append(output, sum%10)
pushToNextIndex = sum / 10
continue
}
output = append(output, sum)
}
//if there is still value after iterating all values then append this as the 
// new array element
if pushToNextIndex > 0 {
output = append(output, pushToNextIndex)
}
fmt.Println(output)
}

如果这不是你想要的,请告诉我!

最新更新