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();
本文介绍了一种基于C/C++实现的简单随机数生成算法,并探讨了其局限性及改进方法。通过具体实例展示了如何生成指定范围内的随机数。

&spm=1001.2101.3001.5002&articleId=3956644&d=1&t=3&u=00ef70fc2e9e47659bb1a9f157563b4f)
3711

被折叠的 条评论
为什么被折叠?



