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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值