我在一个循环中使用rand()每次生成随机数,直到循环完成,但它总是给出相同的数字,我做错了什么?
bool PlayGame(int Difficulty, bool bComplete)
{
int CodeA =rand() % Difficulty + Difficulty;
int CodeB =rand() % Difficulty + Difficulty;
int CodeC =rand() % Difficulty + Difficulty;发布于 2021-09-05 18:54:08
通过在开始时设置srand(time(0));,可以将当前时间用作随机生成器的种子
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Driver program
int main(void)
{
// This program will create different sequence of
// random numbers on every program run
// Use current time as seed for random generator
srand(time(0));
for(int i = 0; i<4; i++)
printf(" %d ", rand());
return 0;
}
Output 1:
453 1432 325 89
Output 2:
8976 21234 45 8975
Output n:
563 9873 12321 24132发布于 2021-09-05 18:56:01
如果在没有首先调用srand()的情况下使用rand()生成随机数,您的程序将在每次运行时创建相同的数字序列。
srand()函数设置产生一系列伪随机整数的起始点。如果未调用srand(),则会将rand()种子设置为srand(1)
因此,在程序开始时设置srand(time(0));
https://stackoverflow.com/questions/69066320
复制相似问题