随机数初探

来源:互联网 发布:淘宝怎么看卖家销量 编辑:程序博客网 时间:2024/06/05 19:55

参考:http://javababy1.iteye.com/blog/1298062

#include <stdio.h>#include <stdlib.h> //ror int rand()#include <string>#include <iostream>#include <time.h>using namespace std;int main(){    //for (int i = 0;i != 100;i++)    //{    //  int a = rand();    //  cout << a << endl;    //}    ////int rand()生成随机数0--RAND_MAX(0x7ffff=32767);但是属于伪随机数,因为多次运行发现,输出是一样的;unsigned int 值范围是0-65536    //如何生成真正意义的随机数——随机种子 。srand()来初始化rand()    //void srand(unsigned int seed=1);参数seed就是用来生成一个随机系列的种子,缺省值是1.    //一般情况下,取当前时间为随机数种子    int b;    srand((unsigned int)time(NULL));    for(b = 0;b != 10;b++)        cout << rand() << endl;    cout << " ——————华丽分割————————" << endl;    //生成100 以内的随机数    for (b = 0;b != 10;b++)        cout << rand() * 100 / 32767 << endl;    system("pause");    return 0;}

结果:

319532099149623554151020560321009766238278480 ——————华丽分割————————7956382498529781373

产生一定范围随机数的通用表示公式
要取得[a,b)的随机整数,使用(rand() % (b-a))+ a;
要取得[a,b]的随机整数,使用(rand() % (b-a+1))+ a;
要取得(a,b]的随机整数,使用(rand() % (b-a))+ a + 1;
通用公式:a + rand() % n;其中的a是起始值,n是整数的范围。
要取得a到b之间的随机整数,另一种表示:a + (int)b * rand() / (RAND_MAX + 1)。
要取得0~1之间的浮点数,可以使用rand() / double(RAND_MAX)。

原创粉丝点击