C 中如何在For中生成不重复的随机数

发布于:2025-02-11 ⋅ 阅读:(38) ⋅ 点赞:(0)

C 中如何在For中生成不重复的随机数

有的时候我们需要在C的For中生成随机数,但是由于For执行的很快,因此我们需要利用到C中高精度时针来作为随机数的种子,从而在每一次的For循环中得到不一样的随机数。
下面将以秒级、微秒级、纳秒级三种时间精度进行测试验证。从实际的结果来看,以纳秒为随机数得到的随机数基本是满足要求的。



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

// gcc CRand.c -lm -o CRand

int CRand_s()
{
    // 采用随机数的形式时间戳
	// time 的单位是 秒
    srand((unsigned)time(NULL));
	int rand_number = (rand() % 5) - 2;;
    return rand_number;
}

int CRand_us()
{

	struct timeval start, end;
	long long int diff;
	long seconds, useconds;
	gettimeofday(&start, NULL); // 获取开始时间
	// 单位 微秒
	usleep(10);
	gettimeofday(&end, NULL); // 获取结束时间
	seconds  = end.tv_sec  - start.tv_sec;
	// 微秒
    useconds = end.tv_usec - start.tv_usec;
	// 计算时间差
	diff = (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec; 
	srand(end.tv_usec);
	// printf("us is %u, %u \n", end.tv_usec, useconds * 10-6);
    int rand_number = (rand() % 5) - 2;
	return rand_number;
}

int CRand_ns()
{
	struct timespec start, end;
    long seconds, nseconds;
    double mtime;
    clock_gettime(CLOCK_MONOTONIC, &start);
	// 单位 秒
	//sleep(1);
	// 单位 微秒
	usleep(10);
    clock_gettime(CLOCK_MONOTONIC, &end);
    seconds  = end.tv_sec  - start.tv_sec;
	// 纳秒
    nseconds = end.tv_nsec - start.tv_nsec;
	// mtime 以毫秒为单位
    mtime = seconds * 1000.0 + nseconds / 1000000.0;
    // 采用随机数的形式时间戳
    srand(end.tv_nsec);
	// printf("ns is %u, %u \n", end.tv_nsec, nseconds * 10-6);
    int rand_number = (rand() % 5) - 2;
	return rand_number;
}

int main()
{
    FILE *fp1, *fp2, *fp3;
    char ch;
    fp1 = fopen("./RecordData1.txt", "w+");
    fp2 = fopen("./RecordData2.txt", "w+");
    fp3 = fopen("./RecordData3.txt", "w+");

    char str_double[44] = {"\0"};
    char temp[8] = {"\0"};

	int rand_number;
    for(int i = 0; i < 5000; i++)
	{
		rand_number = CRand_s();
		gcvt(rand_number, 8, temp);
        fputs(&temp, fp1);
        fputs("\n", fp1);
	}
    for(int i = 0; i < 5000; i++)
	{
		rand_number = CRand_us();
		gcvt(rand_number, 8, temp);
        fputs(&temp, fp2);
        fputs("\n", fp2);
	}
	for(int i = 0; i < 5000; i++)
	{
		rand_number = CRand_ns();
		gcvt(rand_number, 8, temp);
        fputs(&temp, fp3);
        fputs("\n", fp3);
	}

    // 等待文件写入完成
    sleep(10);
    fclose(fp1);
    fclose(fp2);
    fclose(fp3);

    return 0;
}

测试结果

以 纳秒 级为随机数种子到的结果
以 微秒 级为随机数种子到的结果
以 秒 级为随机数种子到的结果


网站公告

今日签到

点亮在社区的每一天
去签到