linux下C语言随机数


linux随机数

linux随机数

linux下真随机数

从linux内核的随机池里取种子,每次都不一样,不可能重复

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/time.h>
    
int fd = open("/dev/urandom",O_RDONLY);
unsigned int seed;
read(fd, &seed, sizeof(seed));
close(fd);
srand(seed);

方案2 伪随机

这里的^是按位异或运算符,把秒数、微妙、进程ID三个值搅和在一起,生成一个每次都不同的随机数种子。

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/time.h>
struct timeval tv;
gettimeofday(&tv, NULL);
srand((unsigned int)(tv.tv_sec ^ tv.tv_usec ^ getpid()));

完整代码

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/time.h>
/*linux 专属随机 
	从linux内核的随机池里取种子,每次都不一样,不可能重复
*/
int randint(int, int);
char get_char(char);
int main()
{
	/*
	// 随机数种子的两个方案
	// 方案1 真随机
	int fd = open("/dev/urandom",O_RDONLY);
	unsigned int seed;
	read(fd, &seed, sizeof(seed));
	close(fd);
	srand(seed);
	*/
	
	// 方案2 伪随机 这里的^是按位异或运算符,把秒数、微妙、进程ID三个值搅和在一起,生成一个每次都不同的随机数种子。
	struct timeval tv;
	gettimeofday(&tv, NULL);
	srand((unsigned int)(tv.tv_sec ^ tv.tv_usec ^ getpid()));
	
	for(int i=0;i<22;i++)
	{
		printf("%c ", get_char('A'));
	}
	printf("\r\n");
	return 0;
}


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

char get_char(char a){
	/*
	// 自己写的随机字符函数
	// 大写'A' 那就大写随机字符,小写'a'那就小写随机字符
	*/
	if(a=='a'){
		return 'a'+randint(0, 25);
	}else if(a=='A'){
		return 'A'+randint(0, 25);
	}
}

简化完整版

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
#include<sys/time.h>


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

int main(){
	struct timeval tv;
	gettimeofday(&tv, NULL);
	srand((unsigned int)(tv.tv_sec^tv.tv_usec));
	for(int i=0;i<11;i++){
		printf("%02d ", randint(1, 31));
	}
	puts("\n");
	return 0;
}
posted @ 2026-10-21 08:50  还在printf  阅读(14)  评论(0)    收藏  举报