【问题标题】:Binary operator '-' cannot be applied to two 'CGFloat' operands二元运算符“-”不能应用于两个“CGFloat”操作数
【发布时间】:2017-04-06 09:18:51
【问题描述】:

我正在编写 3D 游戏并尝试在提取的水龙头的处理程序中编写表达式:

  override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent!) {

    for touch: AnyObject in touches {
        let touchPoint: CGPoint  = touch.location(in: self)

         if (isTracking == true && sqrtf(powf((touchPoint.x - thumbNode.position.x), 2) + powf((touchPoint.y - thumbNode.position.y), 2)) < size * 2)
        {...}
     }
  }

但是Xcode写错了:

二元运算符“-”不能应用于两个“CGFloat”操作数。

比试过了:

 var arg_3 = (touchPoint.x - self.anchorPointInPoints().x)
 var expr_3 = powf(Float(arg_3), 2)
 var arg_4 = (touchPoint.y - self.anchorPointInPoints().y)
 var expr_4 = powf(Float(arg_4),2)
 var expr_5 = expr_3 + expr_4
 var expr_6 = thumbNode.size.width

 if (sqrtf(Float(expr_5)) <= expr_6)
 {}

现在它写道:

二元运算符“

请帮我解决这个问题。

提前致谢。

【问题讨论】:

标签: 3d swift3 pow


【解决方案1】:

您可以使用pow 和sqrt,它们接受并返回CGFloat,这是CGPoint 中值的类型。这样可以避免在您的示例中使用任何强制转换,因为所有内容都将是 CGFloat。

【讨论】:

    【解决方案2】:

    这是一个误导性(错误)的错误消息。

    powf 不接受 CGFloats 作为参数。

    改为创建Float:

    let x = Float(touchPoint.x - thumbNode.position.x)
    powf(x, 2)
    

    编辑:

    解决方法一:

    let y = Float(touchPoint.y - thumbNode.position.y)
    let x = Float(touchPoint.x - thumbNode.position.x)
    if (isTracking == true && sqrtf(powf(x, 2) + powf(y, 2)) < size * 2)
        {...}
    

    解决方法二:

    if (sqrtf(Float(expr_5)) <= Float(expr_6)) ...
    

    【讨论】:

    • 感谢您的想法,但它不起作用。二元运算符“
    • 我的回答没有提到你的第二种方法(&lt;=),而是第一种。请参阅更新的答案。但解决方案是一样的。你也应该用点脑子:-)
    猜你喜欢
    • 2015-08-21
    • 2018-01-18
    • 2016-04-10
    • 2016-09-20
    • 2015-10-22
    • 2015-09-01
    • 2017-11-22
    • 2018-06-23
    • 2023-03-10
    相关资源
    最近更新 更多