VB初学者在这里。我的For ... Next循环不起作用,我不能为我的生活找出原因。我试图在标签和文本框中显示结果,并启用了多行。似乎并不重要。这可能是我在2小时内忽视的明显事物。提前感谢您的帮助。
Option Explicit On
Option Strict On
Option Infer Off
Public Class Form1
Private Sub exitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub displayButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles displayButton.Click
Dim monthly As Double
Dim results As Double
Dim interest As Double
''#clear textbox results
displayLabel.Text = String.Empty
monthlyTextBox.Text = String.Empty
''#calculate the monthly payment due
monthly = -Financial.Pmt(0.06 / 12, 12, 5000)
monthlyTextBox.Text = monthly.ToString("C2")
''#calculate the amounts applied to principal and interest
For per As Integer = 12 To 1 Step -1
results = -Financial.PPmt(0.06 / 12, per, 12, 5000)
interest = monthly - results
displayLabel.Text = results.ToString("C2") & " " & interest.ToString("C2") & ControlChars.NewLine
Next per
displayLabel.Focus()
End Sub
End Class
答案 0 :(得分:2)
问题分为两部分:
总而言之,您在代码运行时看到的是12次迭代的结果。它恰好看起来非常像运行一次迭代。
在这种情况下,我不确定问题1是一个大问题。这是一个足够快的操作,它看起来像一次看到所有结果可能是你想要的。请注意未来的问题。对于第2项,我会像这样编写循环:
''#calculate the amounts applied to principal and interest
Dim resultText As New Text.StringBuilder()
For per As Integer = 12 To 1 Step -1
results = -Financial.PPmt(0.06 / 12, per, 12, 5000)
interest = monthly - results
resultText.AppendFormat("{0:C2} {1:C2}{2}", results, interest, Environment.NewLine)
Next per
displayLabel.Text = resultText.ToString()
我们可以通过利用格式字符串来控制间距并使一切排好,而不是仅仅在术语之间插入几个空格来进一步改进。尝试将此字符串插入.AppendFormat()
来电:
{0,12:C2} {1:C2} {2}
答案 1 :(得分:0)
您要重新分配displayLabel.Text,每次迭代都需要附加到.text字段