其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
关于随机函数

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

             写程序时,常会遇到使用随机函数的地方,这里我给出一种最简单的办法,MSDN中也类似的东西。要想产生真正的随机数还是比较复杂的,但对于大多数应用来说,并不需要。

 示例代码:

//    Name:    rand_example.cpp
// Compile:   cl /EHsc rand_example.cpp
//        OS:    Window 2000 or later

#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>

template <class T>
struct display
{
       void operator()(const T value) { std::cout << value << ' '; }
};

inline int Random(int min,int max)
{
        return ((rand() % (max+1-min))+min);
}

int main()
{
        typedef std::vector<int> IntArray;
        IntArray myarray;

        srand((unsigned int)time(NULL));

        for(int i=0; i < 10; ++i)
               myarray.push_back(Random(10,60));

        for_each(myarray.begin(),myarray.end(),display<int>());

        return 0;
}

       上面的程序中,影响随机数的是能够获取的时间值得精度,如果对精度要求很高,可考虑使用Win32 API  QueryPerformanceCounter来取得更高精度的时间值做为种子值。




相关文章

相关软件