views:

64

answers:

2
 class Class1
 {

[STAThread]
  static void Main(string[] args)
  {

   int lap, avg = 0;
   double time = 0;  
   Random generator = new Random();
   time = generator.Next(5, 10);


   for (lap = 1; lap <= 10; lap++) 

   {

    time = (generator.NextDouble())* 10 + 1;
    Console.WriteLine("Lap {0} with a lap time of {1} seconds!!!!"lap,time.ToString("##.00"));  

   }// end for

    Console.WriteLine("The total time it took is {0}",time);
                  Console.WriteLine();
    Console.WriteLine();
    Console.WriteLine();
    Console.WriteLine("Slap the enter key to continue");
    Console.ReadLine();
  }
 }
}

I'm trying to teach myself c#, however this problem really has me baffled. How do i add the time variable each time through the loop to get the sum of all ten laps? any help would be appreciated thanks :)

+3  A: 

If I got you correctly, you would need to introduce a new variable to keep the total time:

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        int lap, avg = 0;

        Random generator = new Random();

        double time = generator.Next(5, 10);
        double totalTime = 0.0;

        for (lap = 1; lap <= 10; lap++) 
        {
            time = (generator.NextDouble())* 10 + 1;
            Console.WriteLine("Lap {0} with a lap time of {1:##.00} seconds!!!!", 
                lap, time);  

            totalTime += time;
        }

        Console.WriteLine("The total time it took is {0}", totalTime);
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("Slap the enter key to continue");
        Console.ReadLine();
    }
}
0xA3
something so easy....Thanks very much :)
Chris
Sorry for those trying to make it nice, i was also in edit mode...my bad but thanks everyone!
Chris
@Chris: Thanking on SO works by clicking the up-arrows to the left of the question, and by accepting answers by clicking on the check mark next to the question that helped you most.
0xA3
+1 for full example
linuxuser27
i tried clicking up, but i need a reputation of 15 before i can!. So once again Thanks for all your help!
Chris
+2  A: 

You need to include the previous value of time in your addition.

time = time + (generator.NextDouble())* 10 + 1;

or

time += (generator.NextDouble())* 10 + 1;

This of course will cause you to lose the current computed random number. Therefore you should probably create another variable sumTime that will store the sum of all time values.

linuxuser27
That would get you a wrong per-lap time on each iteration > 1.
0xA3
Correct. I edited my solution to mention that creating a new variable would be a good idea. Like yours for instance :)
linuxuser27