跳到正文

个人记录

毫秒级随机数

banned_gutongxing约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年1月6日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 2 分钟
获赞
1

版本

  1. v1当前

众所周知,重复打开相同的可执行文件,想要输出的数不同,往往需要以时间作为随机种子。

如:

C++
#include<bits/stdc++.h>
using namespace std;
signed main(){
	srand(time(0));
	int a = rand();
	printf("%d\n",a);
	return 0;
}

但是,以这种方式,在代码上使用 While\text{While} 下每毫秒随机一个:

但在使用重复运行 exe\text{exe} ,在每 11 秒内重复运行这个程序,输出的随机数都是相同的。

那么,想要打破这个 “1 秒限制”,就需要用到 timeb。

C++
#include<bits/stdc++.h>
using namespace std;
signed main(){
    struct _timeb T;
    _ftime(&T);
    srand(T.millitm);
    int a = rand();
    printf("%d\n", a);
    return 0;
}

这样,在 11 秒内反复执行程序:

可以看到每次执行程序输出的随机数都不同。

这样,就实现 “生成毫秒级别随机数” 了。