decimal p = 10000;
decimal i = 0.04m;
decimal n = 120;
print(CompoundInterest(p, i, n)); //1106625.6080425638107152956764
decimal CompoundInterest(decimal p, decimal i, decimal n) {
if (n<=1) {
return p * (1 + i);
}
return CompoundInterest(p, i, n - 1) * (1 + i);
}
注意:一定要使用decimal类型作为参数,用浮点数的话误差会比较大!
以上为递归的方式计算复利,当然也可以用数学公式,例如:
print(10000 * Mathf.Pow(1.04f, 120)); //1106621,利用数学公式,但是因为浮点数的特性计算有误差,不如上面的结果精确;