当我尝试运行该程序以计算付款和总利息时,我会从字符串"转换为"“转换为’double’无效”。

我究竟做错了什么?

Dim P As Double
Dim R As Double
Dim N As Double
Dim Payment As Double
Dim totalInterest As Double

Private Sub btnAnalyze_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnalyze.Click

P = CDbl(txtAmount.Text)
N = CDbl(txtDuration.Text)
R = CDbl(txtInterestRate.Text)

Payment = (P * R) / (1 - (1 + R) ^ (-N))
totalInterest = (N * Payment) - P

Payment = CDbl(txtPayment.Text)
totalInterest = CDbl(txtInterest.Text)

If P < 0 Then
MessageBox.Show("Please enter in loan amount")

End If

If R <= 0 Then
MessageBox.Show("Please enter in loan amount")

End If

If N <= 0 Then
MessageBox.Show("Please enter in loan amount")

End If


End Sub
End Class

答案

你的其中一位TextBox项目尚未填写。

因此,当您使用CDbl, 例如P = CDbl(txtAmount.Text),如果是TextBox是空的,会导致此错误。

一个更好的选择是使用双重特里普尔斯代替CDbl,因为这将使您能够发出适当的信息:

Private Sub btnAnalyze_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnalyze.Click

If Not Double.TryParse(txtAmount.Text, P) Then
     MessageBox.Show("Please correct the loan amount")
     Exit Sub
End If

' Do the same for all other CDbl checks

来自: stackoverflow.com