2014-11-18 4 views
-1

Я пытаюсь создать программу на Visual Basic 2010, которая вычисляет почасовую зарплату в годовом количестве (например, 10 * 40 * 52) и процентное увеличение этого годового числа и отражают это в течение 10 лет. Моя основная проблема заключается в том, что когда я получаю следующий цикл, который должен повторять математику 9 раз (первый фиксирован), я обнаружил, что код хранит значение с первой итерации и использует это в следующих 8 итерациях , Как я могу избежать этого. Пожалуйста, имейте в виду, что я новичок в программировании, чтобы попытаться сохранить его просто. Благодаря!Для следующей петли, которая вычисляет неправильно?

option Strict On 

Public Class frmPayCalculator 

Private Sub btnComputeFuturePay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComputeFuturePay.Click 
    ' The btnComputeFuturePay event accepts accepts hourly wage and pay raise 
    ' information, and then displays the yearly pay over the next ten years. 

    Dim decHourlyWage As Decimal 
    Dim decYearlyWageComputed As Decimal 
    Dim decExpectedRaise As Decimal 
    Dim decExpectedRaiseComputed As Decimal 
    Dim intYears As Integer 
    Dim decIncrementedYearlyWage As Decimal 

    If IsNumeric(txtHourlyWage.Text) Then 
     ' Convert input to decimal. 
     decHourlyWage = Convert.ToDecimal(txtHourlyWage.Text) 
     ' Data validation to check if input is a positive. 
     If decHourlyWage > 0 Then 
      decYearlyWageComputed = decHourlyWage * 40 * 52 
      lstDecadeWage.Items.Add("Year 1" & " - Wage: " & decYearlyWageComputed.ToString("C")) 
     Else 
      ' Error for negative number 
      lstDecadeWage.Items.Clear() 
      txtHourlyWage.Focus() 
      MsgBox("You have entered a negative number for Hourly' Data validation to check if input is a number. Rate, try again with a positive number", , "Input Error") 
     End If 
     ' Data validation to check if input is a number. 
     If IsNumeric(txtExpectedRaise.Text) Then 
      ' Convert Data to decimal 
      decExpectedRaise = Convert.ToDecimal(txtExpectedRaise.Text) 
      ' Divide the whole number by 100 to make it a percent. 
      decExpectedRaiseComputed = decExpectedRaise/100 
     Else 
      ' Error for non-number: Expected Raise percent. 
      lstDecadeWage.Items.Clear() 
      txtHourlyWage.Focus() 
      MsgBox("You have entered a non-number for the Expected Raise, try again with a number.", , "Input Error") 
     End If 
    Else 
     ' Error for non-number: Hourly Rate. 
     lstDecadeWage.Items.Clear() 
     txtHourlyWage.Focus() 
     MsgBox("You have entered a non-number for Hourly Rate, try again with a number.", , "Input Error") 
    End If 

    For intYears = 2 To 10 
     decIncrementedYearlyWage += (decYearlyWageComputed + decYearlyWageComputed * decExpectedRaiseComputed) 
     lstDecadeWage.Items.Add("Year " & intYears & " - Wage: " & decIncrementedYearlyWage.ToString("c")) 
    Next 

End Sub 

Private Sub mnuClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuClear.Click 
    ' The mnuClear click event that clears the ListBox object, Wage and Raise Textboxes and, enables the Compute 
    ' Future Pay button. 

End Sub 

Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click 
    ' The mnuExit click event closes the window and exits the application. 
    Close() 

End Sub 


Private Sub frmPayCalculator_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    'Preload event that clears the ListBox object, Wage and Raise Textboxes and, enables the Compute 
    ' Future Pay button. 

End Sub 
End Class 

ответ

0

Вместо:

decIncrementedYearlyWage += (decYearlyWageComputed + decYearlyWageComputed * decExpectedRaiseComputed) 

, который собирается дать тот же результат каждой итерации, поскольку значения в формуле не изменяются, то вы могли бы искать что-то вроде этого:

decIncrementedYearlyWage += (decIncrementedYearlyWage * decExpectedRaiseComputed) 
+0

Я знал, что я бегу в некоторой логической ошибки на моем конце. Сначала я не понимал, почему решение работает, но это имеет смысл. Каждый раз, когда итерация выполнялась, значение с итерации сохранялось, а затем использовалось снова и снова. Таким образом, значения в окне списка будут увеличиваться, но только по первому значению. – kl654

0

Например: HourlyWage = 5, ExpectedRaise = 10

с этими данными, если вы пытаетесь сделать следующее:

Year 1 - Wage: $ 10,400.00 
Year 2 - Wage: $ 11,440.00 
Year 3 - Wage: $ 12,584.00 
Year 4 - Wage: $ 13,842.40 
Year 5 - Wage: $ 15,226.64 
Year 6 - Wage: $ 16,749.30 
Year 7 - Wage: $ 18,424.23 
Year 8 - Wage: $ 20,266.66 
Year 9 - Wage: $ 22,293.32 
Year 10 - Wage: $ 24,522.66 

Тогда вы должны сделать:

For intYears = 2 To 10 
    decYearlyWageComputed += decYearlyWageComputed * decExpectedRaiseComputed 
    lstDecadeWage.Items.Add("Year " & intYears & " - Wage: " & decYearlyWageComputed.ToString("c")) 
Next 
Смежные вопросы