我有以下代码:
func pi() -> Double {
func iteration(denominator: Double) -> Double {
let nextNumber: Double = 1.0 / denominator
let isPreciseEnough = abs(nextNumber) < 0.0002
if isPreciseEnough {
return nextNumber
}
let newDenominator = (abs(denominator) + 2.0) * denominator / abs(denominator) * -1.0
return nextNumber + iteration(newDenominator)
}
return 4.0 * iteration(1.0)
}
当我运行它时,它在操场上的第二次运行时停止了访问,当我尝试在项目中构建它时,它停止了
“swift失败,退出代码为1”
我检查了分母的值,第二次运行时它是 2.23690525377983e-314 。但是,当我分开像
这样的方法时func pi() -> Double {
return 4.0 * iteration(1.0)
}
func iteration(denominator: Double) -> Double {
let nextNumber: Double = 1.0 / denominator
let isPreciseEnough = abs(nextNumber) < 0.0002
if isPreciseEnough {
return nextNumber
}
let newDenominator = (abs(denominator) + 2.0) * denominator / abs(denominator) * -1.0
return nextNumber + iteration(newDenominator)
}
它完美无缺。任何人都可以解释,为什么顶部的例子不起作用?