You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中正确实现抵押贷款月供计算公式?

如何在C#中正确实现抵押贷款月供计算公式?

我太懂这种感觉了——纸上算公式明明没问题,一写成代码就卡壳,甚至AI还给添乱,真的闹心。先看看你写的这段代码,核心逻辑其实是对的,不过我帮你把细节理清楚,再说说容易踩的坑:

首先是调整后的完整实现代码,我优化了注释让逻辑更清晰:

static double CalculateMonthlyRepayment(double loanAmount, double annualInterestRate, int loanTermYears)
{
    // 将年化利率转换为月利率,注意:这里的annualInterestRate需要是小数形式(比如5%要传入0.05)
    double monthlyInterestRate = annualInterestRate / 12.0;

    // 将贷款年限转换为总还款月数
    int loanTermMonths = loanTermYears * 12;

    // 等额本息月供计算公式
    double monthlyPayment = loanAmount * (monthlyInterestRate * Math.Pow(1 + monthlyInterestRate, loanTermMonths)) /
        (Math.Pow(1 + monthlyInterestRate, loanTermMonths) - 1);

    return monthlyPayment;
}

这里要重点提醒一个极易踩的坑:年化利率的输入格式。如果用户习惯输入百分比数值(比如输入5代表5%),那一定要在代码开头加一步转换,否则计算出的月供会严重偏离实际:

annualInterestRate = annualInterestRate / 100.0;

你提到的困扰特别真实:

I could do it on a piece of paper but translating it into code is something I'm struggling with. Even tried using AI but it just made it worse.

其实你已经把核心的等额本息公式写对了,大概率是没注意到利率格式这种细节,或是AI生成的代码引入了多余的错误逻辑。你可以用经典案例测试:比如贷款100000元、年化利率5%、贷款30年,月供约为536.82元,用这个数值就能快速校验代码是否正确。

备注:内容来源于stack exchange,提问作者Jaydon Ellick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 12:45:27