Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

c++ - Same random numbers every time I run the program

My random numbers that output, output in the same sequence every time I run my game. Why is this happening?

I have

#include <cstdlib> 

and am using this to generate the random numbers

randomDiceRollComputer = 1 + rand() % 6;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to seed your random number generator:

Try putting this at the beginning of the program:

srand ( time(NULL) );

Note that you will need to #include <ctime>.

The idea here is to seed the RNG with a different number each time you launch the program. By using time as the seed, you get a different number each time you launch the program.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...