为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕雪6442864 2022-12-19 20:21:32
如何在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)}
查看完整描述

1 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

从你的问题的输入和输出样本来看,你似乎需要为两个输入数组取 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)

 }

请 lemmy 知道这是否不是您要找的!


查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信