【问题标题】:Binary operator '/' cannot be applied to two (Int) operands [duplicate]二元运算符'/'不能应用于两个(Int)操作数[重复]
【发布时间】: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


【解决方案1】:

尽管出现错误消息,但您似乎无法转发序列 (...) 运算符。在agv() 函数中调用sumOf(numbers) 会导致错误cannot invoke sumOf with an argument of type ((Int))

【讨论】:

    【解决方案2】:

    错误告诉你该怎么做。如果参考https://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_operators.html

    /  Division.
    A binary arithmetic operator that divides the number to its left by the number to its right.
    Class of operands: integer, real
    Class of result: real    
    

    第二个参数必须是真实的。像这样转换它。我不使用xcode,但我认为我的语法是正确的。

    var avg:Float = ( sumOf(numbers) ) / Float( numbers.count ) 
    

    【讨论】:

    • 除以两个整数在 Swift 中非常好。它返回不带余数的整数商。这不是 AppleScript ;-)
    • @vadian 好的,请赐教。为什么错误说它不适用于两个整数?为什么文档会说同样的话?
    • 文档引用来自 AppleScript 文档,不同的语言 - 不同的规则。错误消息显示.. two (Int) operands - 带括号的 Int 与 Int 不同
    • 如上所述,我对此了解不多。我猜当时很多人对 Swift 的看法是错误的。 [这是这个的副本](stackoverflow.com/questions/24181082/…)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    相关资源
    最近更新 更多