在 for 循环中将随机生成的数字相加
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();
}
}
}
我正在尝试自学 C#,但是这个问题确实让我感到困惑。如何每次通过循环添加时间变量以获得所有十圈的总和?任何帮助将不胜感激谢谢:)
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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我的理解正确,您将需要引入一个新变量来保留总时间:
If I got you correctly, you would need to introduce a new variable to keep the total time:
您需要在添加中包含之前的
time
值。time = time + (generator.NextDouble())* 10 + 1;
或
time += (generator.NextDouble())* 10 + 1;
这当然会导致您丢失当前计算的随机数。因此,您可能应该创建另一个变量
sumTime
来存储所有time
值的总和。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 alltime
values.