- C++11之前,没有自带的random函数,要生成随机数,普遍采用rand和srand()。
- C++11之后,内部提供了强大的随机数库Random。
rand()
其内部实现是用线性同余法做的,生成是可看做一定范围内随机的伪随机数,其最大范围和系统相关。
通用公式:
- a + rand() % n;其中的a是起始值,n是整数的范围。
- 或 a+(int)b * rand() / (RAND_MAX + 1)。
- 要取得0~1之间的浮点数,可以使用rand() / double(RAND_MAX)
#include <iostream> #include <cstdlib> using namespace std; int main() { for (int i = 0; i < 10; i++)//输出十次 { cout << rand()%100<< " ";//范围在[0,100)的随机数 } return 0; }注意:没有随机种子,多次重复运行,产生的随机数结果是相同的。
srand()
srand()可用来设置rand()产生随机数时的随机数种子。
- 通过设置不同的种子,我们可以获取不同的随机数序列。
- 例如,使用srand((int)(time(NULL))的方法,利用系统时钟,产生不同的随机数种子。不过要调用time(),需要加入头文件ctime。
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand((int)time(0)); // 产生随机种子 把0换成NULL也行 for (int i = 0; i < 10; i++)//产生十次 { cout << rand()%100<< " ";//范围在[0,100)的随机数 } return 0; }插入随机种子后,多次运行代码,随机数的结果不同。
为了方便使用,可以使用宏定义:#include <iostream> #include <cstdlib> #include <ctime> #define random(x) rand()%(x) using namespace std; int main() { srand((int)time(0)); // 产生随机种子 把0换成NULL也行 for (int i = 0; i < 10; i++) { cout << random(100) << " "; } return 0; }
本文介绍了C++11引入的强大随机数库Random,对比了旧版的rand和srand函数,展示了如何使用随机种子生成不同序列的随机数,并给出了代码示例。
2万+

被折叠的 条评论
为什么被折叠?



