2014-12-07 46 views
0

我是第一年的编程学生,正在努力制作按揭付款计算器。用户输入他们的贷款金额和利率,选择15或30年的期限长度,他们的每月付款应计算。我认为数学是正确的,但我认为我遇到了转换数据类型的问题。我能够计算的唯一结果是“无限”。我也试着将所有变量声明为双精度,但没有区别。由于Visual Basic中的按揭付款计算中收到“infinity”

下面是我遇到的一段代码,Option Strict On包含在完整的代码中。任何提示将非常感谢!

Dim decLoanAmount As Decimal 
    Dim decInterestRate As Decimal 
    Dim decFifteen As Decimal = 180D 
    Dim decThirty As Decimal = 360D 
    Dim decNumberOfMonths As Decimal 
    Dim dblPayment As Double 
    Dim decPayment As Decimal 

    ' Did user enter a numeric value? 

    If IsNumeric(txtLoanAmount.Text) And IsNumeric(txtInterestRate.Text) Then 
     decLoanAmount = Convert.ToDecimal(txtLoanAmount.Text) 
     decInterestRate = Convert.ToDecimal(txtInterestRate.Text) 

     ' Is Loan Amount greater than zero? 
     If decLoanAmount > 0 And decInterestRate > 0 Then 
      If radFifteen.Checked = True Then 
       decNumberOfMonths = decFifteen 
      ElseIf radThirty.Checked = True Then 
       decNumberOfMonths = decThirty 
      End If 

      ' Calculate the monthly payments as a double 
      dblPayment = (decLoanAmount * (decInterestRate/12/100) * (1 + (decInterestRate/12/100) _ 
       ^decNumberOfMonths))/((1 + (decInterestRate/12/100)^decNumberOfMonths) - 1) 
      ' Convert double to decimal 
      decPayment = Convert.ToDecimal(decPayment) 
      ' Display monthly payment 
      lblPayment.Text = decPayment.ToString("C2") 

     Else 
      If decLoanAmount < 0 Then 
       MsgBox("Please enter a valid loan amount.", , "Input error") 
      End If 

      If decInterestRate < 0 Then 
       MsgBox("Please enter a valid interest rate.", , "Input error") 
      End If 

     End If 

    Else 
     ' Display error message if user entered a negative value. 
     MsgBox("Please enter a numeric value.", , "Input Error") 
    End If 
End Sub 
+1

我建议保理出来了一下,检查值就像你所期望的那样 - 例如,在计算过程中会重复'(decInterestRate/12/100)',所以为什么不先计算它,然后检查这个值是否如你所期望的那样。 – 2014-12-07 21:08:49

+1

此外,'decPayment = Convert.ToDecimal(decPayment)'不会做很多... – 2014-12-07 21:09:59

+1

您不希望人们在这里为您编写和/或调试代码,对吧?向我们展示一些研究,提供样本输入,输出,更多解释。假设上面的代码不在那里,你认为你描述的内容足以帮助你吗? – Neolisk 2014-12-07 21:48:08

回答

0

根据Wikipedia formula,您的操作不正确。它应该是这个样子:

dblPayment = (decLoanAmount * (decInterestRate/(12 * 100)))/(1 - (1 + (decInterestRate/(12 * 100)))^(-decNumberOfMonths)) 

而且,这条线是怪异

decPayment = Convert.ToDecimal(decPayment) 

应该

decPayment = Convert.ToDecimal(dblPayment)