View Single Post
 
Old 12-03-2014, 03:03 AM
naton naton is offline
Freshman
 
Join Date: Aug 2004
Posts: 30
Default I thought that Double and Integer are initilised to Zero by Default

Hi there,
I'm using Visual Studio 2005, and my VB code is misbehaving. I initially thought it was a bug in Visual Studio, but updating it with Service Pack 1 did not solve this issue.

Basically, in the code below, the variable "average" is not reset to zero but retains its value from the previous loop. It is behaving as a public variable.

Am I doing something wrong?

Code:
Class Car
   private power as Double
   private shared rnd as Random = new Random (1234)

   Public Sub New(Byval maxPower as Double)
      power = rnd * maxPower
   End Sub

   Public Function MyPower() as double
      Return power
   End Function
End Class

Class FleetOfCar
   private cars() as Car
   
   Public Sub New(Byval numberOfCars as Integer, Byval maxPower as Double)
      ReDim cars(numberOfCars - 1)

      For i as Integer = 0 to numberOfCars - 1
         cars(i) = New Car(maxPower)
      next
   End Sub

   ' Here is the issue. the variable "average" passed to this function retains the value from
   ' the previous loop instead of been reset to zero.
   Public Sub ComputeAverage(Byref average as double, Byval thresholdPower as double)
       For i as Integer = 0 to cars.GetUpperBound(0)
          if cars(i).MyPower > thresholdPower Then average++
       Next

       average = average / cars.Length
   End Sub
End Class

Public Sub Main()
   Dim MyFleetOfCars as FleetOfCars
   Dim maxPower as Double = 200
   Dim numCars as integer = 20

   For i as Integer = 0 to 10
      FleetOfCars = New FleetOfCars(numCars, maxPower)

      Dim average as Double      ' This variable is not reset to zero after each loop
      FleetOfCars.ComputeAverage(average, maPower / 2)
      Console.WriteLine(average)
   Next 
End Sub

Last edited by naton; 12-03-2014 at 03:09 AM.
Reply With Quote