C++ 中生成随机数需用到srand() 和 rand() 两个函数 ( #include
步骤一: 使用void srand(time(NULL) );设置seed ,一般time(NULL) ( #include
步骤二:使用 int rand() ; 获得一个[0,RAND_MAX(0x7fff)) 直接的随机整数。
要想取得[a,b)之间的随机整数,使用(rand()%(b-a))+ a,结果包含 a 而不含 b 。
例子:
// C++随机函数(VC program)
#include <stdio.h>
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char* argv[])
{ srand( (unsigned)time( NULL ) );//srand()函数产生一个以当前时间开始的随机种子.
int a=5,b=10;
for (int i=0;i<10;i++)
cout<<rand()%(b-a)+a <<endl;//MAX为最大值,其随机域为[a,b)
return 0;
}
原文链接: https://www.cnblogs.com/wenshanzh/archive/2012/08/21/2649816.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/60398
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!