byte[] date=new byte[28];
            byte[] bytes = new byte[4];
            for (int i = 0; i < 3; i++)//生成12位的3项电流
            {
                double dou;
                int n;
                Random ra = new Random();
                dou = ra.NextDouble();
                float ran = (float)(dou * 100);           
                bytes = BitConverter.GetBytes(ran);
                n = 15 + i * 4;
                Array.Copy(bytes,0,date,n,4);
            }
            Single A_value = BitConverter.ToSingle(date,15);
            Single B_value = BitConverter.ToSingle(date,19);
            Single C_value = BitConverter.ToSingle(date,23);  
        }这段代码很简单就是实现生成3个单精度随机数,每个随机数都存在字节数组里,每个随机数占数组的4个单元,我单步执行的时候能够生成理想的3个单精度数,但是我断点执行,断点设在循环结束后的第一句话相当于执行完循环再暂停程序,这时候观察ABC3个变量的值居然是一样的....能不能看出毛病在哪

解决方案 »

  1.   

    byte[] date=new byte[28];
      byte[] bytes = new byte[4];
      Random ra = new Random();
      for (int i = 0; i < 3; i++)//生成12位的3项电流
      {
      double dou;
      int n;
      dou = ra.NextDouble();
      float ran = (float)(dou * 100);  
      bytes = BitConverter.GetBytes(ran);
      n = 15 + i * 4;
      Array.Copy(bytes,0,date,n,4);
      }
      Single A_value = BitConverter.ToSingle(date,15);
      Single B_value = BitConverter.ToSingle(date,19);
      Single C_value = BitConverter.ToSingle(date,23);  
      }
      

  2.   


    1楼正解:  byte[] date=new byte[28];
      byte[] bytes = new byte[4];
      Random ra = new Random(); //<--- 注意这句在for外面!!!
      for (int i = 0; i < 3; i++)//生成12位的3项电流
      {
      double dou;
      int n;
      dou = ra.NextDouble();
      float ran = (float)(dou * 100);  
      bytes = BitConverter.GetBytes(ran);
      n = 15 + i * 4;
      Array.Copy(bytes,0,date,n,4);
      }
      Single A_value = BitConverter.ToSingle(date,15);
      Single B_value = BitConverter.ToSingle(date,19);
      Single C_value = BitConverter.ToSingle(date,23);  
      }
      

  3.   


    1楼的回复就是这题的正解!
    注意 Random ra = new Random(); 放到了 for 的外面。
      

  4.   

    Random ra = new Random();
    放在外面
    不重复Random ra = new Random(DateTime.Now.Millisecond);