In this example, I show some simple random generator examples using C++.
It simulates the generator of INT and FLOAT. The generator format is [a,b] or [a,b).
//////////////////////////////////////////////////////////////////////////
//
// Test the random generator of INT and float
//
#include <iostream>
#include <time.h>
void main()
{
TestRandomIntFloatACM();
}
static void TestRandomIntClose(int ,int );
static void TestRandomFloatClose(float ,float);
static void TestRandomInt(int ,int );
static void TestRandomFloat(float ,float);
</pre>
<!--more-->
<pre class="brush: cpp; ruler:true ">//////////////////////////////////////////////////////////////////////////
//
//
//
void TestRandomIntFloatACM()
{
// test the generator of INT
TestRandomIntClose(1,10);
TestRandomInt(1,10);
// test the generator of FLOAT
TestRandomFloatClose(1.0f,10.0f);
TestRandomFloat(1.0f,10.0f);
}
//////////////////////////////////////////////////////////////////////////
//
// generate int [a,b)
//
void TestRandomInt(int a,int b)
{
srand(unsigned(time(NULL)));
std::cout << "Generate int data [" << a << "," << b <<")" << std::endl;
for(int i=0;i<10;++i)
{
int generateInt = rand()%(b-a) + a;
std::cout << generateInt << " " ;
}
std::cout << std::endl;
}
//////////////////////////////////////////////////////////////////////////
//
// generate int [a,b]
//
void TestRandomIntClose(int a,int b)
{
srand(unsigned(time(NULL)));
std::cout << "Generate int data [" << a << "," << b <<"]" << std::endl;
for(int i=0;i<10;++i)
{
int generateInt = rand()%(b-a+1) + a;
std::cout << generateInt << " " ;
}
std::cout << std::endl;
}
//////////////////////////////////////////////////////////////////////////
//
// generate float [a,b)
//
void TestRandomFloat(float a,float b )
{
srand(unsigned(time(NULL)));
std::cout << "Generate float data [" << (float)a << "," << (float)b <<")" << std::endl;
float range = b-a;
for(int i=0;i<10;++i)
{
double generateFloat = a + (range*rand()/(RAND_MAX+0.0));
std::cout << generateFloat << std::endl ;
}
std::cout << std::endl;
}
//////////////////////////////////////////////////////////////////////////
//
// generate float [a,b]
//
void TestRandomFloatClose(float a,float b )
{
srand(unsigned(time(NULL)));
std::cout << "Generate float data [" << (float)a << "," << (float)b <<"]" << std::endl;
float range = b-a;
for(int i=0;i<10;++i)
{
double generateFloat = a + (range*rand()/(RAND_MAX-1.0));
std::cout << generateFloat << std::endl ;
}
std::cout << std::endl;
}
[1]. something about the function "rand()" : http://wenku.baidu.com/view/34caf9c708a1284ac8504318.html