【问题标题】:Binary operator '*' cannot be applied to operands of type 'Double' and 'Int' [duplicate]二元运算符'*'不能应用于'Double'和'Int'类型的操作数[重复]
【发布时间】:2021-10-04 00:58:49
【问题描述】:

我在这个网站上尝试了一些解决方案,但没有想出一个。

这行代码我一直收到这个错误:

func futureValue() {
    let interest = Double(interestInput.text!) ?? 0
    let pv = Double(pvInput.text!) ?? 0
    let years = Double(yearsInput.text!) ?? 0
        
    let result = pv * (1.0 + interest) ^^ years
}

result 变量是我收到错误的地方。我做错了什么?

【问题讨论】:

  • 兴趣、pv 和年份可以为 0,swift 会将它们解释为 Int。但是在您的结果计算中,您使用的是 1.0,它是双精度数。尝试使用?? 0.0 而不是 ?? 0
  • @SwissMark 很好的建议,但这不起作用。仍然抛出同样的错误..
  • ^^ 运算符需要哪些类型?我敢打赌,它预计将成为 Int
  • @Rob 一针见血。做到了!谢谢。

标签: ios swift multiplication


【解决方案1】:

为了回答这个问题,自定义 ^^ 运算符设置为 Int 而不是 Double

这是不正确

}

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
    return Int(pow(Double(radix), Double(power)))

这是正确的方式,匹配futureValue()函数中的Double

}

precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Double, power: Double) -> Double {
    return Double(pow(Double(radix), Double(power)))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多