2016-07-23 178 views
0

所以我想使用我的數組中的數據將其添加到變量。變量名稱是newValue。我有一個名爲numbers一個數組,這是它看起來像如何獲取數組中的所有數據並將其存儲在新變量或常量中?

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

我還有一個變種是和「無功總和= 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的文本編輯器中。非常感謝你們。

回答

1

你的錯誤是因爲你要添加Int[Int],即一個Int到Array <Int>(只能添加的屬性相同Type),您需要做的是通過訪問element,counter作爲Index值,將Int添加到元素Array<Int>

使用計數器的值作爲指標值來從 檢索每個數組,並添加

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 
+0

非常感謝您的幫助。我現在得到它,並將再次查看邏輯! :) –

0

如果要計算陣列的你可以試試這個總和......

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

感謝您的回答,但它不是我所期待的。我目前正在快速學習,並在teamtreehouse.com上面對代碼挑戰。挑戰狀態:現在我們已經建立了while循環,是時候計算總和了! 使用計數器的值作爲索引值,從數組中檢索每個值並將其添加到sum值。 例如:sum = sum + newValue。或者你可以使用複合加法運算符sum + = newValue,其中newValue是從數組中檢索的值。 –

0

如果添加類型它可以幫助您變量。

  1. 注意你初始化numbers作爲Integers陣列,並且 總和是一個Integer。這兩個不能相加。

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

  2. 您使用的是while循環,可以使用for-infor-each

  3. 當循環您聲明var NewValue = numbers,也許考慮到decleare var newValue = 0只有一次外循環

  4. 回到你的問題,如果你仍然想使用while循環,和最小變化。注意評論

    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 
    } 
    
相關問題