首页 > 解决方案 > Swift:初始化程序 'init(_:)' 要求 'Decimal' 符合 'BinaryInteger'

问题描述

我正在尝试创建一个计算并返回复利的函数。变量具有不同的数据类型。每当我运行程序时,都会出现错误initializer 'init(_:)' requires that 'Decimal' conform to 'BinaryInteger'。以下是我的代码:

import Foundation

class Compound{
    var p:Double
    var t:Int
    var r:Double 
    var n:Int 
    var interest:Double
    var amount:Double 
    init(p:Double,t:Int,r:Double,n:Int){
        self.p = p
        self.t = t
        self.r = r
        self.n = n        
    }

    func calculateAmount() -> Double { 
        amount = p * Double(pow(Decimal(1 + (r / Double(n))),n * t))
        return amount
    }

}

错误:

error: initializer 'init(_:)' requires that 'Decimal' conform to 'BinaryInteger'
        amount = p * Double(pow(Decimal(1 + (r / Double(n))),n * t))
                     ^

在查看了类似的问题后,我也尝试了以下技术,但我仍然遇到同样的错误

func calculateAmount() -> Double { 
        let gg:Int = n * t
        amount = p * Double(pow(Decimal(1 + (r / Double(n))),Int(truncating: gg as NSNumber)  ))
        return amount
    }

如何解决这个问题?

标签: iosswift

解决方案


考虑到您要返回 Double ,使用 Doublefunc pow(_: Double, _: Double) -> Double而不是使用 Decimal会更容易:func pow(_ x: Decimal, _ y: Int) -> Decimal

@discardableResult
func calculateAmount() -> Double {
    amount = p * pow(1 + (r / Double(n)), Double(n) * Double(t))
    return amount
}

推荐阅读