【发布时间】:2015-06-30 16:04:52
【问题描述】:
当我将以下代码放入 Xcode 中的 Swift Playground 时,我收到 Binary operator '/' cannot be applied to two (Int) operands 错误。
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
上面是一个计算任意数字总和的函数。
下面是一个计算数字平均值的函数。该函数从自身内部调用sumOf() 函数。
func avg(numbers: Int...) -> Float {
var avg:Float = ( sumOf(numbers) ) / ( numbers.count ) //Binary operator '/' cannot be applied to two (Int) operands
return avg
}
avg(1, 2, 3);
注意:我在堆栈交换中到处寻找答案,但所有问题都与我的不同,因为我的问题涉及两个 Ints,相同类型而不是不同的两种不同类型。
如果有人可以帮助我解决我遇到的问题,我会很高兴。
【问题讨论】:
-
对于从 Google 获得此问题且情况不涉及“数字列表”问题的其他人,另请参阅this question 的答案。本质上,如果 A 已经声明为 CGFloat 的 Double 或其他类型,并且 B 和 C 是整数,则 A = B / C 将失败并显示此错误消息,这掩盖了真正的问题和解决方案: A = Double(B/C) .
标签: xcode swift swift-playground