#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]) {
srand((unsigned)time(NULL));
printf("%d\n", rand()%100+1);
printf("%d", rand()%100+1);
return 0;
}
我已经运行了很多次,每次第一个值都稳定增加,就像2 5 9 17 24 30 ..... 91 97 3 7 12(但该值始终不同)。奇怪的是,第二个值正常执行,这可能是什么问题?
您几乎是正确的,我也不知道发生这种情况的确切或正确原因。
但是我用以下代码解决了这个问题:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char *argv[])
{
srand(time(NULL));
for (;;) // running infinitely here until program's interrupted
{
printf("%d\n", rand() % 100 + 1);
printf("%d", rand() % 100 + 1);
printf("\n---\n");
sleep(1);
}
return 0;
}
如果将srand(time(NULL))
放在无限循环之外,并将其包含在无限循环中,它将可以正常工作。此后,您将获得两个值在每次迭代中随机更改,而不仅仅是增加(第一个值)。