gpt4 book ai didi

c# - 在for循环中添加随机生成的数字的总和

转载 作者:太空宇宙 更新时间:2023-11-03 20:39:22 27 4
gpt4 key购买 nike

 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 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();
}
}

关于c# - 在for循环中添加随机生成的数字的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3705003/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com