gpt4 book ai didi

arrays - 快速显示重复循环中的数组输出

转载 作者:行者123 更新时间:2023-11-28 16:19:24 27 4
gpt4 key购买 nike

我正在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com