亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 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 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號