随机序列在c中看起来不是随机的
Random sequence looks not random in c
我正在实现一个生成 2 个随机数的基本程序。问题是第一个数字的结果看起来遵循某种模式,但第二个看起来仍然正确。
输出:
6584 679
6587 1427
6591 9410
6594 156
7733 3032
7737 3780
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(NULL));
int a = rand()%10001, b= rand()%10001;
printf("%d %d", a,b);
return 0;
}
那么这里的问题是什么以及如何解决它。
如有任何帮助,我们将不胜感激。
我正在使用 windows 10 64 位,gcc 8.1.0。
time(NULL) 值在您每次 运行 程序时充当相同的种子值。您的 CPU 每次都会生成类似的起始 NULL 时间的原因。要摆脱这种效果,您需要使用种子值,这样即使您的计算机以相同的时间 (NULL) 值启动,它也需要获得与其他 运行 不同的种子。为此,您只需执行以下操作:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(){
srand((unsigned)time(NULL) * (unsigned)getpid());
int a = rand()%10001, b= rand()%10001;
printf("%d %d", a,b);
return 0;
}
完全归功于@pmg,感谢您提出改进解决方案的意见。
我正在实现一个生成 2 个随机数的基本程序。问题是第一个数字的结果看起来遵循某种模式,但第二个看起来仍然正确。
输出:
6584 679
6587 1427
6591 9410
6594 156
7733 3032
7737 3780
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(NULL));
int a = rand()%10001, b= rand()%10001;
printf("%d %d", a,b);
return 0;
}
那么这里的问题是什么以及如何解决它。
如有任何帮助,我们将不胜感激。
我正在使用 windows 10 64 位,gcc 8.1.0。
time(NULL) 值在您每次 运行 程序时充当相同的种子值。您的 CPU 每次都会生成类似的起始 NULL 时间的原因。要摆脱这种效果,您需要使用种子值,这样即使您的计算机以相同的时间 (NULL) 值启动,它也需要获得与其他 运行 不同的种子。为此,您只需执行以下操作:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(){
srand((unsigned)time(NULL) * (unsigned)getpid());
int a = rand()%10001, b= rand()%10001;
printf("%d %d", a,b);
return 0;
}
完全归功于@pmg,感谢您提出改进解决方案的意见。