ksacvet777.moy.su
Главная » Статьи » IT

Получение случайного целого

Получение случайного значения для 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;
}

 

Категория: IT | Добавил: ksacvet777 (05.11.2014)
Просмотров: 298 | Теги: int, Random, unsigned | Рейтинг: 0.0/0
Всего комментариев: 0
Имя *:
Email *:
Код *: