我是一名编程第一年的学生,我正在尝试制作抵押贷款计算器。用户输入他们的贷款金额和利率,选择15或30年的期限长度,并计算他们的每月付款。我认为数学是正确的,但我认为我遇到了转换数据类型的问题。我能够计算的唯一结果是" 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
答案 0 :(得分:0)
根据Wikipedia formula,您无法正确执行此操作。看起来应该是这样的:
dblPayment = (decLoanAmount * (decInterestRate / (12 * 100))) / (1 - (1 + (decInterestRate / (12 * 100))) ^ (-decNumberOfMonths))
此外,这条线很奇怪
decPayment = Convert.ToDecimal(decPayment)
应该是
decPayment = Convert.ToDecimal(dblPayment)