2013-10-07 2 views
0

나는 처음부터 다시 시작했으며 누적 합계 2 개를 제외하고 모든 것이 의도 한대로 작동하지만 계산이 원하는 방식으로 작동하지 않습니다. 이전 판매량을 합계에 추가하는 대신 끝에 새로운 판매량을 추가합니다 ...VB.NET - 누적 수 및 평균 계산

예를 들어 : 1 스노우 보드와 1 스노우 보드 (부츠 포함)를 입력하면 스노우 보드와 스노우 보드의 요약에 1이 표시됩니다 부츠와. 그러나 내가 판매량을 줄이기 위해 다시 입력을 시도 할 때 문제가 발생하면 1 스노우 보드와 1 스노우 보드 부츠를 입력하고 요약은 2가 아닌 11을 표시합니다. 왜 이런 일이 발생합니까?

' Declare module-level variables and constants. 
Private SnowBoardsSold, BootsSold, SaleCount As Integer 
Private ItemsSold As Integer 
Private TotalSales As Decimal 
Const SNOWBOARD_RATE As Decimal = 20D 
Const BOOTS_RATE As Decimal = 30D 


Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click 
    ' Calculate the prices 
    Dim SnowBoards, Boots As Integer 
    Dim SnowBoardSale, BootsSale, ThisSale, AverageSalesEver As Decimal 

    Try 
     ' Convert the Snowboard input to numeric variable. 
     SnowBoards = Integer.Parse(SnowboardsTextBox.Text) 

     Try 
      ' Convert Boots if Snowboard was successful. 
      Boots = Integer.Parse(WithBootsTextBox.Text) 
      ' Calculate values for sale. 
      SnowBoardSale = SnowBoards * SNOWBOARD_RATE 
      BootsSale = Boots * BOOTS_RATE 
      ThisSale = SnowBoardSale + BootsSale 

      ' Calculate summary values. 
      TotalSales += ThisSale 
      BootsSold += BootsSale 
      SnowBoardsSold += SnowBoardSale 
      SaleCount += 1 
      AverageSalesEver = TotalSales/SaleCount 

      ' Format and display prices for the sale. 
      SnowBoardsPriceTextBox.Text = SnowBoardSale.ToString("c") 
      BootsPriceTextBox.Text = BootsSale.ToString("c") 
      TotalPriceTextBox.Text = ThisSale.ToString("c") 

      ' Format and display values for the summary. 
      SnowBoardRentalTextBox.Text += SnowBoards.ToString() 
      BootsRentalTextBox.Text += Boots.ToString() 
      TotalChargesTextBox.Text = TotalSales.ToString("c") 
      AverageChargeTextBox.Text = AverageSalesEver.ToString("c") 

     Catch BootsException As FormatException 
      ' Handle a Boots exception. 
      MessageBox.Show("Please enter numbers.", "Data Entry Error", 
          MessageBoxButtons.OK, MessageBoxIcon.Error) 
      With WithBootsTextBox 
       .Focus() 
       .SelectAll() 
      End With 
     End Try 

    Catch SnowBoardsException As FormatException 
     ' Handle a SnowBoard exception. 
     MessageBox.Show("Please enter numbers.", "Data Entry Error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error) 
     With SnowboardsTextBox 
      .Focus() 
      .SelectAll() 
     End With 

    Catch AnException As Exception 
     'Handle any other exception. 
     MessageBox.Show("Error: " & AnException.Message) 
    End Try 
End Sub 
+1

변수가 잘못되어 – Plutonix

+0

에 초점을 맞출 수 있습니다. AverageChargeInteger 변수가 올바르지 않고 SnowboardSaleCountInteger 및 WithBootsSaleCountInteger가 예상대로 합쳐지지 않습니다. –

+1

각 계산에 대해 함수를 만들 것입니다. 사실 각 추상화를 별도의 하위 또는 람다로 분리하십시오. 이렇게하면 코드를 이해하기 쉽게 읽을 수 있습니다. 내 다른 제안은 당신이 얻고있는 결과와해야 할 결과를 보여주는 예입니다. – jcwrequests

답변

0

첫째, 당신은 당신이 숫자를 잡아 방식을 변경할 수 있습니다 :

'Convert snowboard input value to numeric variable. 
SnowboardInteger = Integer.Parse(SnowboardsTextBox.Text) 

에 :

Dim SnowboardInteger As Integer 
If TryParse.Integer(SnowboardsTextBox.Text, SnowboardInteger) = False then 
' if it parses, SnowboardInteger will have the value, 
'else the function returns false 
    MessageBox.Show("Please enter numbers") 
End if 

는 또한, 당신은 두 번 텍스트 상자를 분석하고 있습니다. 한 번 선언 다음에 그 후에. 이 모양이 올바르지 않습니다.

SnowboardSaleCountInteger += 1 
WithBootsSaleCountInteger += 1 
TotalSaleCountInteger += TotalChargesSumInteger ' ????? 
AverageChargeInteger = TotalChargesSumInteger/TotalSaleCountInteger 

'카운터'에 '요금'을 추가하는 것이 올바르게 보이지 않습니다. 당신이 평균 야해 원하는 경우가있을 : 전체 달러가 할당 확인하지 않는 한

TotalSaleCountInteger = SnowboardSaleCountInteger + WithBootsSaleCountInteger 

당신이 그런 결과에서 'XX.YY'로 분수를 원하는 경우

AverageChargeInteger는 더블 또는 소수이어야한다.

이전 클릭에서 누적해야하는 경우 절차에서 일부 선언을 SnowboardSumInteger, WithBootsSumInteger까지 이동하여 누적 될 수 있도록해야합니다. 그것은 그렇습니다. WithBootsSaleCountInteger, TotalSaleCountInteger은 아무 것도하지 않으며 항상 1입니다. 'SaleCounter'로서 텍스트 상자의 값으로 증가하지 않아야하는지 궁금합니다. 단지 1 (나 앞에서 과제가 없습니다)입니다.

당신이해야 할 수도 있습니다 한가지 더 여기에 있습니다 :

SnowboardPriceInteger = SnowboardInteger * SNOWBOARD_RENTAL_RATE 
WithBootsPriceInteger = WithBootsInteger * WITH_BOOTS_RENTAL_RATE 
TotalPriceInteger = SnowboardPriceInteger + WithBootsPriceInteger 

귀하의 상수 진수 (SNOWBOARD_RENTAL_RATE이) 그래서, 석회질의 결과가 소수의 VAR에 가야하지만, SnowboardPriceInteger 다른 하나는있다 아니. 정수는 곱셈 또는 나눗셈의 분수 결과를 저장할 수 없습니다. 같은

뭔가 :

' sales accumulators 
Private TotalSales As Decimal = 0 
Private ItemsSold As Integer = 0 

클릭 이벤트 :

' this sale: 
Dim Snowboards As Integer 
Dim Boots As Integer 

' get the values from the text boxes, then: 
Dim SnowBoardSale As Decimal = (SnowBoards * SnowBoardRate) 
Dim BootsSale As Decimal = (Boots * BootsRate) 
Dim ThisSale As Decimal = SnowBoardSale + BootsSale 

' update accumulators 
TotalSales += ThisSale 
ItemsSold += (Boots + Snowboards) 

' calc the average 
Dim AverageSalesEver AS Decimal = TotalSales/ItemsSold 

' Display results in textboxes 
'(this exercise is left to the student ;) ) 

HTH

난 당신이 너무 많은 변수와 오래된 시도에서 남은 사람과 자신을 혼동 생각합니다.

+0

더 많은 정보가 필요하다고 생각합니다. 아마 정수 수학과 관련이 있습니다. 이상적으로 정수를 mixin하는 대신 double-out을 사용해야합니다. – jcwrequests

+0

그 역시 평균 계산이 잘못 보입니다. – Plutonix

+0

계산이 함수로 분리 된 다음 예제를 사용하여 주석을 작성하면 더 자세한 정보를 얻을 수 있습니다. – jcwrequests