Adding up the sum of random generated numbers in a for loop
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 = (generato开发者_开发百科r.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 :)
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();
}
}
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.
精彩评论