Linux下產生隨機正整數

 

 

/*************************************************************    
    FileName : rand.c
    FileFunc : 產生隨機整型正整數  
    Version  : V0.1    
    Author   : Sunrier    
    Date     : 2012-05-11
    Descp    : Linux下產生隨機正整數(範圍1到RAND_MAX)   
*************************************************************/
#include <stdio.h>
#include <stdlib.h>

int MyRand( void )
{
	struct timeval tpstart;
	int iRet;
	
	gettimeofday(&tpstart,NULL);
	srand(tpstart.tv_usec);//通過使用微妙,來增加隨機數的隨機性
	iRet = (1+(int)(300.0*rand()/(RAND_MAX+1.0)));//產生1到RAND_MAX之間的整數
	
	return iRet;
}

int main(int argc,char *argv[])
{
	int iTime,iValue;
	for(iTime=0 ;iTime<10 ;iTime++ )
	{
		iValue =  MyRand();
		printf("iTime%d = %d \n",(iTime+1),iValue);
		sleep(1);
	}
	
	printf("RAND_MAX  = %d \n",RAND_MAX);
	
	return 0;
}


 

 

 

/*************************************************************    
    FileName : rand.c
    FileFunc : 產生隨機長整型正整數  
    Version  : V0.1    
    Author   : Sunrier    
    Date     : 2012-05-11
    Descp    : Linux下產生長整型正整數 
*************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/timeb.h>
#include <math.h>

long LongRand( void )
{
	struct timeb tp;
	unsigned short time_seed[3];
	long lRet;

	ftime(&tp);
	time_seed[0]=tp.millitm * tp.millitm;
	time_seed[1]=tp.millitm;
	time_seed[2]=tp.time/tp.millitm;
	lRet=jrand48(time_seed);
	return fabs(lRet);
}

int main(int argc,char *argv[])
{
	int iTime;
	long lValue;
	
	for(iTime=0 ;iTime<10 ;iTime++ )
	{
		lValue = LongRand();
		printf("iTime%d = %d \n",(iTime+1),lValue);
		sleep(1);
	}
	
	return 0;
	
}


 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章