在for循环中累加随机生成的数字的总和

时间:2010-09-13 22:52:13

标签: c# loops sum 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 = (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#,不过这个问题让我感到困惑。如何通过循环每次添加时间变量以获得所有十圈的总和?任何帮助将不胜感激,谢谢:)

2 个答案:

答案 0 :(得分:3)

如果我找对你,你需要引入一个新变量来保持总时间:

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

答案 1 :(得分:2)

您需要在添加中添加time的先前值。

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

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

这当然会导致您丢失当前计算的随机数。因此,您应该创建另一个变量sumTime,它将存储所有time值的总和。