C ++随机函数返回相同的数字 [英] C++ random function return same numbers
本文介绍了C ++随机函数返回相同的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图获取范围从0到3的随机数。使用这样的代码:
#include< cstdlib>
int index = rand()%3;
但总是得到相同的结果: 1 1 0 1
。
我做错了什么?总是相同的数字。
解决方案
您忘记了广告
#include< ctime>在程序开始时
srand(time(NULL))
这将根据当前时间每次运行程序时生成一个新的种子。
I'm trying to get random numbers on range from 0 to 3. Using such code:
#include <cstdlib>
int index = rand() % 3;
But always getting the same results: 1 1 0 1
.
What I'm doing wrong? Always the same numbers. Results should change their values after each compilation or during runtime?
解决方案
Your forgot to ad
#include <ctime>
srand(time(NULL))
at the start of your program.
This will generate a new seed everytime you run your program based on the current time.
这篇关于C ++随机函数返回相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文