【问题标题】:How do I get all the data from an array and store it in a new variable or constant?如何从数组中获取所有数据并将其存储在新变量或常量中?
【发布时间】:2016-07-23 10:34:56
【问题描述】:

所以我尝试使用数组中的数据将其添加到变量中。变量名是newValue。我有一个名为numbers 的数组,这就是它的样子

let numbers = [2,8,1,16,4,3,9]

我有另一个 var 是 sum 'var sum = 0'。最后还有一个叫柜台var counter = 0

所以!这是我所有的代码。

let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0

while counter < numbers.count {
    var newValue = numbers
    sum = sum + newValue
    counter++
}

如您所见,我正在尝试将值添加到我的 var newValue 中。怎么样?

很抱歉代码看起来像那样,但是当我尝试制作多行代码块时它不起作用。如果有人知道然后告诉我。否则,您可以将代码放在某种 idk 的文本编辑器中。非常感谢大家。

【问题讨论】:

    标签: arrays swift loops while-loop


    【解决方案1】:

    你的错误是因为你将Int添加到[Int],即一个Int到Array &lt;Int&gt;(你只能添加相同Type的属性),你需要做的是添加Int和元素Array&lt;Int&gt; 通过counter 访问element 作为Index 值。

    使用 counter 的值作为索引值检索每个 value 数组并添加

    let numbers = [2,8,1,16,4,3,9]
    var sum = 0
    var counter = 0
    
    while counter < numbers.count {
        var newValue = numbers
        sum = sum + newValue[counter] // use counter to access element of Array
        counter += 1 // also ++ is deprecated // now use += 1 instead 
    }
    
    print(sum) // 43
    

    【讨论】:

    • 非常感谢您的帮助。我现在明白了,将再次查看逻辑! :)
    【解决方案2】:

    如果你想计算数组的总和,你可以试试这个......

    let numbers = [2,8,1,16,4,3,9]
    var sum = 0
    for each in numbers {
        sum = sum + each
    }
    print(sum)  //Prints -->> 43
    

    【讨论】:

    • 感谢您的回答,但这不是我想要的。我目前正在快速学习,并且在 teamtreehouse.com 上遇到了代码挑战。挑战指出:现在我们已经设置了 while 循环,是时候计算总和了!使用 counter 的值作为索引值,从数组中检索每个值并将其添加到 sum 的值。例如:sum = sum + newValue。或者,您可以使用复合加法运算符 sum += newValue,其中 newValue 是从数组中检索到的值。
    【解决方案3】:

    如果将类型添加到变量中可能会有所帮助。

    1. 请注意,您将 numbers 初始化为 Integers 的数组,并且 sum 是一个Integer。这两个不能相互添加。

      var sum: Int = 0代替var sum = 0

    2. 您正在使用while 循环,可以使用for-infor-each 循环

    3. 循环时声明var NewValue = numbers,可能考虑只在循环外解除var newValue = 0一次

    4. 回到您的问题,如果您仍想使用while 循环,并且最少更改。注意cmets

      let numbers = [2,8,1,16,4,3,9]
      var sum = 0
      var counter = 0
      
      while counter < numbers.count {
         // var newValue = numbers //new value is now array and that's not what you want
         var newValue = numbers[counter] // I think that is the change you are looking fot 
         sum = sum + newValue
         counter += 1  // ++ is deprecated in swift
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 2022-01-23
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      相关资源
      最近更新 更多