我试图在一个简单的数学应用程序中编写一个计算平均值的函数。我没有得到任何错误,但代码输出没有显示在我的Xcode操场的右侧边栏。它在我的代码中输出两个零,并在那里停止。有什么问题吗?
func averageOf(numbers: Int...) -> Float {
var sum = 0
var numberTotal = 0
for number in numbers {
sum += number
numberTotal = numbers.count
}
return Float(sum / numberTotal)
}
averageOf()
averageOf(10, 56, 75, 90, 109)
最佳答案
当您调用averageOf()
时,它似乎会导致操场崩溃(除以零,因为numberTotal
是0
)。
例如,如果你这样称呼它:
averageOf(10, 56, 75, 90, 109)
averageOf(10, 20, 30)
averageOf()
averageOf(10, 20, 30)
前两个调用会得到一个输出,但后两个调用不会。
更新3(贷记@wumm)
如果您单击右面板上的任何变量或打开一个助理编辑器,您将看到错误(尽管很奇怪):
Playground execution failed: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
* thread #1: tid = 0x1c4a02, 0x000000010aff7e14, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
* frame #0: 0x000000010aff7e14
解决办法是最后检查数字总数。而且,顺便说一下,不需要在循环中分配它:)
以下是一个固定版本:
更新:开头的cheching numbertotal确实更合理(归功于@kovpas):
更新2:更改了
return
部分。归功于`@martinr.func averageOf(numbers: Int...) -> Float {
var numberTotal = numbers.count
if numberTotal == 0 {
return 0
}
var sum = 0
for number in numbers {
sum += number
}
return Float(sum)/Float(numberTotal)
}
averageOf(10, 56, 75, 90, 109)
averageOf(10, 20, 30)
averageOf()
averageOf(10, 20, 30)