ios - 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
}
如何解决这个问题?
解决方案
考虑到您要返回 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
}
推荐阅读
- wordpress - 如何使用 css 为不同的页面添加单独的标题图像
- object-detection - 我应该为验证图像创建 json 注释吗?
- javascript - javascript Date 对象中的时区问题
- javascript - 在数组中查找薪水最高的部门
- python - 在查询中使用 ndb IN 运算符
- ide - 为什么 WebStorm IDE 中的文件无法正常工作?
- python - 为什么我在生成pdf时在reportlab中出现“内存错误”
- docker - 如何使用 BUILDBOT_CONFIG_URL 配置 buildbot docker 容器
- angular - 从 API 请求 Angular 添加路由不适用于 SSR
- python - 如何将单列作为数据框内的标题传递:我面临错误:必须使用某种集合调用索引(...)