Получение случайного значения для int и для unsigned int
#include <stdlib.h>
#include <time.h>
#include <assert.h>
// proto
unsigned int random_uint();
int random_u(int nMin, int nMax) ;
size_t random_biased_version( size_t low , size_t high ) ;
//
// implement
//
unsigned int random_uint()
{
static int stime = 0;
if( stime == 0)
{
stime= (int)(time(NULL)/2);
srand(stime);
}
unsigned int res = (unsigned int)rand() * (unsigned int)rand();
return res;
}
int random_u(int nMin, int nMax)
{
static int stime = 0;
if( stime == 0)
{
stime= (int)(time(NULL)/2);
srand(stime);
}
return nMin + (int)((double)rand() / (RAND_MAX+1) * (nMax-nMin+1));
}
size_t random_biased_version( size_t low , size_t high )
{
static int stime = 0;
if( stime == 0)
{
stime= (int)(time(NULL)/2);
srand(stime);
}
unsigned int r=0;
do
{
r = rand();
} while (r < ((unsigned int)(RAND_MAX) + 1) % (high + 1 - low));
return r % (high + 1 - low) + low;
}
|