您的位置:首页 > 编程语言 > C#

使用VS2005 C#编写随机数Random算法的代码(适用于连续产生随机数,重置后不适用)

2009-03-04 15:17 686 查看

using System;


using System.Collections.Generic;


using System.ComponentModel;


using System.Data;


using System.Drawing;


using System.Text;


using System.Windows.Forms;


using System.IO;


using System.Collections;




namespace RandomFunction




...{


public partial class Random : Form




...{


public Random()




...{


InitializeComponent();


}




private void btnExit_Click(object sender, EventArgs e)




...{


Application.Exit();


}




static UInt64 next = 1;




//从同一个种子开始


private int PeRandom( )




...{


next = next * 1103515245 + 12345;


return (UInt16)(next / 65536) % 32768;


}




private void btnRandom_Click(object sender, EventArgs e)




...{


int input_MaxNum;


int output_num;




//输入随机数的范围 0 --- input_MaxNum


input_MaxNum = int.Parse(inputRandom.Text);




output_num = this.PeRandom();




try




...{


listOutput.Items.Add(output_num % input_MaxNum);


}


catch (System.ApplicationException ex)




...{


Console.WriteLine(ex.Message);


}






}




private void btnClr_Click(object sender, EventArgs e)




...{


listOutput.Items.Clear();


}




}


}

下面这段代码是随机函数的核心部分:

next = next * 1103515245 + 12345;
return (UInt16)(next / 65536) % 32768;

读者可以尝试着把1103515245,12345替换掉,也会产生随机数,next / 65536相当于把next向右移16位,然后% 32768,因此取值范围在(0--32767)之间。

细心的朋友发现每次第一次产生的数其实未必随机,都是固定的,只是后面每个数不一样罢了。因此这种随机算法受到了局限,很多随机函数还与时间函数相关联,这样只要不在同一时刻产生的数就不会一样了,当然精确到毫秒级别同一时刻是相对困难的。

故,以上算法适用与连续不断产生随机数的需求,如果系统重置,每次重置所产生的随机数是相同的,这一点需要注意。

源代码下载处:

http://download.csdn.net/source/334547

c/cpp中可以产生随机种子,在用rand函数,就避免了重复
srand((unsigned)time(NULL));
rand();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐