找不到接受提供的参数的'+'

时间:2015-06-18 09:12:04

标签: swift xcode6

我正在尝试制作月度贷款支付计算器 这是代码:

import UIKit

class monthlypayment: UIViewController {



@IBOutlet weak var loanamounttextfield: UITextField!
@IBOutlet weak var numberofmonthstextfield: UITextField!
@IBOutlet weak var loanpercentagetextfield: UITextField!
@IBOutlet weak var answerlabel: UILabel!

@IBAction func calculate(sender: AnyObject) {
    var loanamounttext = loanamounttextfield.text
    var loanamount:Double! = Double((loanamounttext as NSString).doubleValue)
    var loanpercentage = loanpercentagetextfield.text
    var loanpercentagedouble:Double! = Double((loanpercentage as NSString).doubleValue)
    var numbrofmonths = numberofmonthstextfield.text
    var numberofmonths:Double! = Double((numbrofmonths as NSString).doubleValue)
    var rate = loanpercentagedouble/1200
    var monthlypayment:Double = rate+(rate/(1.0+rate)^numberofmonths)-1.0*loanamount
    }
}

我在这里收到错误

        var rate = loanpercentagedouble/1200
        var monthlypayment:Double = rate+  (rate/(1.0+rate)^numberofmonths)-1.0*loanamount

如你所见,numberofmonths和loanamount是双倍的

但我收到错误: 找不到接受提供的参数的“+”

1 个答案:

答案 0 :(得分:2)

在Swift中^是XOR运算符(返回各种Ints)而不是指数,你想使用pow(num, power)函数

var monthlypayment = rate + pow(rate / (1.0 + rate), numberofmonths) - 1.0 * loan amount

或者,您可以定义自定义运算符

infix operator ** { associativity left precedence 160 }

func ** (left: Double, right: Double) -> Double {
    return pow(left, right)
}

并将您的代码重写为更易读的

var monthlypayment = rate + (rate / (1.0 + rate)) ** numberofmonths - 1.0 * loanamount