随机函数rand在实际编程中经常会用到,比如随机颜色、随机数字等。
随机数函数介绍:
随机函数定义在头文件<cstdlib>中,使用rand随机函数时要先#include头文件。
1 |
int rand(); |
rand()返回0—RAND_MAX中随机的一个整数,RAND_MAX是最大随机数值,是个宏定义
1 2 3 4 5 |
/* * RAND_MAX is the maximum value that may be returned by rand. * The minimum is zero. */ #define RAND_MAX 0x7FFF |
随机数函数编程实测:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//梁笔记 //zouzhongliang.com #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { for(int i =0;i<10;i++) cout<<rand()<<endl; return 0; } |
运行结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
运行第一次结果 41 18467 6334 26500 19169 15724 11478 29358 26962 24464 运行第二次结果 41 18467 6334 26500 19169 15724 11478 29358 26962 24464 运行第三次结果 41 18467 6334 26500 19169 15724 11478 29358 26962 24464 |
从结果来看发现有不对的地方,每次运行的随机数都与上次运行的随机数一样??这点将在下面讲解为什么。
随机数函数编程注意点
rand()的产生依赖于一个发生器序列,这时需要调用srand()函数来初始化发生器,(如果不初始化就是默认,所以每次运行随机数都一样)这个初始值一般称为随机种子。
1 |
void srand(unsigned int seed); |
一般srand的参数会直接给一个时间的毫秒数(time(0))作为这个种子。
上面代码加入随机种子后:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//梁笔记 //zouzhongliang.com #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand(time(0)); for(int i =0;i<10;i++) cout<<rand()<<endl; return 0; } |
输出结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
运行第一次结果 14765 3115 21165 8289 524 12649 18468 28592 26435 24980 运行第二次结果 14785 2070 30046 21596 29644 3441 4375 11028 27201 20859 运行第三次结果 14814 502 26984 8790 24171 6014 32387 17451 11965 31063 |
这样使用随机函数才能做到真的随机!
You’ve made your point! Does Provigil Help With Concentration
Regards! Useful information! celex
You made the point! cialis generic
Very good data. With thanks. https://viagrapycharm.com/
You made your position extremely clearly!. herbal salvation kratom
Really tons of amazing material! pharmacy on line
Truly a good deal of amazing knowledge. global pharmacy canada
You actually reported it perfectly! viagra online
Lovely postings, Thanks a lot. modafinil
Truly plenty of terrific advice. 200 Mg Of Provigil
Thanks. I appreciate this! Cymbalta Long Term Studies
Thanks a lot. I value this! Provigil And Hepatitis C
Point clearly taken.! fluconazole
You mentioned this really well. side effects for modafinil
Beneficial info. Cheers! canada drugs
Wonderful forum posts. Thanks a lot. modafinil side effects