如何让"rand()"产生真正的随机数?
How to make "rand()" generate actual random numbers?
我得到了这个代码:
#include <stdio.h>
#include <conio.h>
int rand();
int main()
{
int a = 1;
while (a<=15)
{
printf("%d\n", rand());
a++;
}
return 0;
}
生成随机数的函数在每次执行时生成相同的数字,我该如何解决?
您需要像这样用 srand()
初始化您的 rand()
:
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int a = 1;
while (a<=15)
{
printf("%d\n", rand());
a++;
}
return 0;
}
简而言之,你需要给你的随机数一些种子,这样它才能完成他的工作,但你想在每个 运行 给他新的种子,因此使用 time(NULL)
。
哦,还有,你不需要在你的 main 之前声明 int rand();
,而是将 <stdlib.h>
添加到你的包含列表中。
继续学习!
您必须设置一个种子,所以只需在您的 while 循环之前执行此操作(同时不要忘记包括:time.h
):
srand(time(NULL));
您可以使用
生成不同的随机数
#include <stdlib.h> // for rand() and srand()
#include <time.h> // for time()
// other headers
int main()
{
srand(time(NULL));
// rest of your code
}
通过使用 srand()
,您可以为随机数生成器设置种子,以便在程序的不同运行中获得不同的随机数。
并从您的代码中删除 int rand();
,除非您尝试创建自己的 rand()
函数
种子或srand(time(NULL));
如果你设置时间,包括<time.h>
库。
我向您推荐了 include <stdlib.h>
- 这是用于 srand 或 rand 函数的。
我得到了这个代码:
#include <stdio.h>
#include <conio.h>
int rand();
int main()
{
int a = 1;
while (a<=15)
{
printf("%d\n", rand());
a++;
}
return 0;
}
生成随机数的函数在每次执行时生成相同的数字,我该如何解决?
您需要像这样用 srand()
初始化您的 rand()
:
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int a = 1;
while (a<=15)
{
printf("%d\n", rand());
a++;
}
return 0;
}
简而言之,你需要给你的随机数一些种子,这样它才能完成他的工作,但你想在每个 运行 给他新的种子,因此使用 time(NULL)
。
哦,还有,你不需要在你的 main 之前声明 int rand();
,而是将 <stdlib.h>
添加到你的包含列表中。
继续学习!
您必须设置一个种子,所以只需在您的 while 循环之前执行此操作(同时不要忘记包括:time.h
):
srand(time(NULL));
您可以使用
生成不同的随机数#include <stdlib.h> // for rand() and srand()
#include <time.h> // for time()
// other headers
int main()
{
srand(time(NULL));
// rest of your code
}
通过使用 srand()
,您可以为随机数生成器设置种子,以便在程序的不同运行中获得不同的随机数。
并从您的代码中删除 int rand();
,除非您尝试创建自己的 rand()
函数
种子或srand(time(NULL));
如果你设置时间,包括<time.h>
库。
我向您推荐了 include <stdlib.h>
- 这是用于 srand 或 rand 函数的。