每次运行程序时使用相同的随机数 [英] Same random numbers every time I run the program

查看:123
本文介绍了每次运行程序时使用相同的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的随机数输出,每次我运行我的游戏输出在相同的序列。为什么会发生这种情况?



我有

  #include< cstdlib> 

并使用此来生成随机数字

  randomDiceRollComputer = 1 + rand()%6; 


解决方案

p>

尝试将它放在程序的开头:

  srand (空值) ); 

请注意,您需要 #include< ctime>



这里的想法是每次启动程序时用不同的数字播种RNG。通过使用时间作为种子,您每次启动程序时都会得到不同的数字。


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;

解决方案

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.

这篇关于每次运行程序时使用相同的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆