首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

用 C# 寫個人住房貸款計算機(四)

     編輯:關於C語言

該類別中的 Round 方法用於決定在計算時如何進行捨入,如有需要,可以修改該方法。

在該類別的 GetMonthRate 方法中,根據貸款期數來判斷是該筆貸款是短期貸款還是中長期貸款,從而決定應該使用什麼利率。

表示等本息法的 LoanEq 類別是從 LoanBase 類別中衍生的:

using System;
using System.Drawing;
using System.Collections.Generic;

namespace Skyiv.Ben.LoanCalculator
{
    // 等本息法
    sealed class LoanEq : LoanBase
    {
        public LoanEq(decimal balance, int months, DateTime date, KeyValuePair<DateTime, PointF>[] rates)
            : base(balance, months, date, rates)
        {
        }

        protected override void Calculate(decimal balance, int months, DateTime date, KeyValuePair<DateTime, PointF>[] rates)
        {
            decimal baseAmount = 0, totalAmount = 0, totalInterest = 0;
            decimal monthRate0 = decimal.MinValue, monthAmount = decimal.MinValue;
            for (int month = months; month >= 1; month--, date = date.AddMonths(1))
            {
                var monthRate = GetMonthRate(date, months, rates);
                var interest = Round(balance * monthRate);
                if (monthRate0 != monthRate) monthAmount = GetMonthAmount(balance, monthRate0 = monthRate, month);
                baseAmount = monthAmount - interest;
                balance -= baseAmount;
                if (month == 1 && balance != 0)
                {
                    baseAmount += balance;
                    interest -= balance;
                    balance = 0;
                }
                totalAmount += monthAmount;
                totalInterest += interest;
                Table.Rows.Add(new object[] { months - month + 1, date, baseAmount, interest, monthAmount, balance, totalAmount, totalInterest });
            }
        }

        decimal GetMonthAmount(decimal balance, decimal monthRate, int months)
        {
            double tmp = Math.Pow(1 + (double)monthRate, months);
            return Round((decimal)((double)balance * (double)monthRate * tmp / (tmp - 1)));
        }
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved