日期:2014-05-18  浏览次数:20917 次

帮我看看这个奇怪的问题,困扰了我很久!
为何我单步运行的时候每次出现的数字不一样,一旦用for循环输出的数字都是一样的了,包括用数组输出的时候也是一样的结果,请大家帮助!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using rocktest;
using System.Collections;
namespace rocktest
{
  class programm
{
  public static int PoissonRandomNumber(double Lemda)
  {
  double u;
  int Z = 0;
  double L;
  double p = 1.0;
  L = Math.Exp(-Lemda);
  Random rand = new Random();

  do
  {
  Z = Z + 1;
  u = rand.NextDouble();
  p = p * u;

  }
  while (p >= L);
  return Z - 1;
  }
  static void Main(string[] args)
  {
  //for (int i = 0; i < 10; i++)
  Console.WriteLine(rocktest.Program.BinomialRandom(0.5, 10));

  }
}
}

------解决方案--------------------
楼主怎么还没明白呢?:(

C# code

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using rocktest; 
using System.Collections; 
namespace rocktest 
{ 
  class programm 
{ 
  static Random rand = new Random();
  public static int PoissonRandomNumber(double Lemda) 
        { 
            double u; 
            int Z = 0; 
            double L; 
            double p = 1.0; 
            L = Math.Exp(-Lemda); 

            do 
            { 
                Z = Z + 1; 
                u = rand.NextDouble(); 
                p = p * u; 

            } 
            while (p >= L); 
            return Z - 1; 
        } 
          static void Main(string[] args) 
          { 
                //for (int i = 0; i < 10; i++) 
            Console.WriteLine(rocktest.Program.BinomialRandom(0.5, 10)); 

            } 
} 
}