可被零异常整除

时间:2018-10-29 00:50:46

标签: c#

我正在为某位员工进行贷款计划付款的计算,并且我不断得到

  

ClassName:“ System.DivideByZeroException”,消息:“试图除以零。”

我不知道自己在做什么错,也许我的小数位数转换不好。

private static decimal ReturnPayments(decimal loanAmount, int durationMonths, decimal interestMonthly)
{
   return (loanAmount * interestMonthly)/ (decimal) (1-Math.Pow((int)(1 
                                                                      + interestMonthly), -durationMonths));
}
public IEnumerable<LoanRepaymentSchedule> GetRepayment(string employeeId, decimal principalAmt, decimal rate, int terms)
{
   var employee = _employeeService.FindByAsync(e => e.Id == employeeId 
                                                    && e.Status == EntityStatus.Active).Result;
   var results = employee.FirstOrDefault();
   var currentBalance = principalAmt - 0;
   decimal monthlyRate = rate / 1200;
   var monthlyPaymentAmt = ReturnPayments(currentBalance, terms, monthlyRate);
   var result = new List<LoanRepaymentSchedule>();
   for (var currentPayment =1; currentPayment<= terms; currentPayment++)
   {
      decimal interestAmount = currentBalance * monthlyRate;
      decimal deductedBalance = monthlyPaymentAmt - interestAmount;
      currentBalance = currentBalance - deductedBalance;

      var monthlyDetail = new LoanRepaymentSchedule
         {

            Balance = currentBalance,
            PrincipalAmt = deductedBalance,
            InterestAmt = interestAmount,
            TotalAmt =monthlyPaymentAmt,
            EmployeeId = results.Id

         };

      result.Add(monthlyDetail);

   }
   return result;
}

1 个答案:

答案 0 :(得分:6)

在我看来,您的问题出在这里:

return (loanAmount * interestMonthly) / (decimal)(1 - Math.Pow((int)(1 + interestMonthly), -durationMonths));

具体地说,在这里:

(int)(1 + interestMonthly)

假设interestMonthly的值是0.05(即5%),那么我们进行计算:

1 + interestMonthly = 1.05
(int)(1.05) = 1

在其余方法的范围内,您将有效地执行Math.Pow(1, -durationMonths),这将给您1,然后执行1 - 1,这将给您0。您将其除以0并得到异常。

您的问题的原因:整数不能存储分数,因此强制转换为整数基本上会忽略该值的非整数部分。您可能应该将其从(int)更改为(double)以便与Math.Pow()方法一起使用:

return (loanAmount * interestMonthly) / (decimal)(1 - Math.Pow((double)(1 + interestMonthly), -durationMonths));