My Accumulator for my For… Next loop is skipping numbers in VB; Visual Studio 2010.

StackOverflow https://stackoverflow.com/questions/10193511

  •  01-06-2021
  •  | 
  •  

문제

I am trying to write a For... Next loop that will allow for 12 entries, or the cancel button.
Somehow intEntries is only using 1, 3, 5, 7, 9, and 11. After that is completed the calculation is being divided by 13, and not 12. I'm not sure what it is I've got wrong, but it's apparently something. Any Assistance you can give me is greatly appreciated!

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        'initialize accumulator
        Dim decEntries As Decimal
        ' For loop to ask for input.
        For decEntries = 1 To 12 Or strMonthlyAvg = " "
            strMonthlyAvg = InputBox("Please Enter the Average for Month # " & decEntries & ":")
            decEntries += 1
            lstTemps.Items.Add(strMonthlyAvg)
            decMontlyAvg = Convert.ToDecimal(strMonthlyAvg)
            ' This will add the montly average to the total Average Temperature for 
            ' calculations
            decTotalTemp += decMontlyAvg

        Next
        ' Calculation to provide the average temp for all entered values
        decAnnualAvg = decTotalTemp / decEntries
        ' convert annual average to string
        strAnnualAvg = Convert.ToString(decAnnualAvg)
        ' Display the results for the user
        lblResults.Text = "The average annual temperature " & vbCrLf &
                            "based on your entries is: " & strAnnualAvg & "."


    End Sub
도움이 되었습니까?

해결책

remove the line decEntries += 1 the for .. loop increase by one automatically!

다른 팁

You have decEntries as the counter in the For-Next loop, which increments each time the Next is reached.

However, you are also incrementing it 'manually' in the middle of the loop:

decEntries += 1 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top