循环中的VB.Net意外添加?

时间:2014-06-17 08:45:43

标签: vb.net

程序应该将用户输入的值输入textbox1(目标级别)并将其用于变量exp的计算,然后将最终结果输出到{{1 }}。 然而,结果出错了。

这是exp系统:

label3

所以公式为:Each lvl require 2 exp more than the previous lvl. lvl1-2 = 1 exp (1 exp) lvl2-3 = 3 exp (4 exp) lvl3-4 = 5 exp (9 exp) lvl4-5 = 7 exp (14 exp) lvl5-6 = 9 exp (23 exp) (从n-1级到n级需要exp)

然后循环用于对所需的所有exp进行求和,以给出从0exp到目标等级所需的总exp。

以下是输入数字时程序输出的内容:

1 = (2*n) - 3

2 = 0

3 = 1

4 = 6

5 = 15

以下是预期/正确的输出:

1 = 28

2 = 0

3 = 1

4 = 4

5 = 9

这是实际的程序:

14

2 个答案:

答案 0 :(得分:3)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As Integer
Dim exp As Integer = 0

Label3.Text = ""

If TextBox1.Text <> "" Then
    x = Convert.ToInt32(TextBox1.Text)

    For i As Integer = 2 To x
        exp += (2 * i) - 3     '<- ERROR HERE
    Next

    Label3.Text = exp.ToString
End If

End Sub

您总是添加5 xp级别,而不是当前级别的xp。

答案 1 :(得分:1)

试试这个

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As Integer
Dim exp As Integer = 0

Label3.Text = ""

If TextBox1.Text <> "" Then
    x = Convert.ToInt32(TextBox1.Text)

    For i As Integer = 2 To x
        exp += (2 * i) - 3
    Next

    Label3.Text = exp.ToString
End If
End Sub