我正在 Swift 3 Playground 中进行练习。
我有一个名为 sums 的数组,里面有一堆数字。我想循环遍历每个数组项并打印“总和是:x”,但打印命令出现一般错误。
var i = 0
repeat {
print ("the sum is: \(sums[i])")
i = i + 1
} while i <= sums.count
有谁知道我做错了什么?
它必须在重复循环中完成,因为这就是练习所要求的。
最佳答案
sums.count 将为您提供数组的大小。 数组在 Swift 中是从 0 开始索引的。您正在访问数组范围之外。 检查 sums.count - 1 或:
var i = 0
repeat {
print ("the sum is: \(sums[i])")
i = i + 1
} while i < sums.count
关于arrays - 快速显示重复循环中的数组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38663275/