我希望得到1到10之间的随机数.它确实有效,但是当它处于循环中时,我并不真正得到随机数.
int randomNum;
srand ( (unsigned int)time(NULL) );
randomNum = rand() % 10;
Run Code Online (Sandbox Code Playgroud)
我已经花了几个小时在这里和谷歌寻找解决方案,但它看起来没有人真正解决它(或者我可能没有足够的搜索).我们从随机函数得到的值取决于秒(不是毫秒或其他东西,就像在其他编程语言中),这就是数字不是随机的原因.
另外,我不想下载C语言包,因为我在大学实验室运行我的代码,他们不会允许它.
有没有人有这个问题的创意解决方案?也许是一些数学函数?
为了说明Sidoh的答案.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(int argc, char** argv)
{
int i;
srand ( (unsigned int)time(NULL) );
for (i = 0; i < 100; i++)
{
printf("%d ", 1 + (rand() % 10));
}
putchar('\n');
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这使用time()为我的一次种子产生了以下结果.
7 10 2 4 4 4 2 1 7 7 10 4 3 10 2 9 6 9 2 9 7 10 4 1 1 8 2 4 8 1 2
4 2 3 9 5 8 1 7 4 9 8 10 1 8 1 1 5 1 4 5 7 3 9 10 3 6 1 9 3 4 10
8 5 2 7 2 2 9 10 5 9 8 4 1 7 7 2 3 7 5 8 6 10 8 5 4 3 7 2 8 2 1 7
7 5 5 10 6 5
Run Code Online (Sandbox Code Playgroud)