C++生成随机数
来源:互联网 发布:云收银软件 编辑:程序博客网 时间:2024/05/16 16:17
1,一般情况,生成随机数采用以下方式:
#include <stdio.h>#include <stdlib.h>#include <time.h>int main (){ int iSecret, iGuess; /* initialize random seed: */ srand ( time(NULL) ); /* generate secret number: */ iSecret = rand() % 10 + 1; do { printf ("Guess the number (1 to 10): "); scanf ("%d",&iGuess); if (iSecret<iGuess) puts ("The secret number is lower"); else if (iSecret>iGuess) puts ("The secret number is higher"); } while (iSecret!=iGuess); puts ("Congratulations!"); return 0;}
2,但是实际这种方式生成的随机数并不是很随机,有时候随机变化的幅度很小,而《Accelerated C++》提供了一种不错的方式:
// return a random integer in the range `[0,' `n)'int nrand(int n){if (n <= 0 || n > RAND_MAX)throw domain_error("Argument to nrand is out of range");const int bucket_size = RAND_MAX / n;int r;do r = rand() / bucket_size;while (r >= n);return r;}
3,上面这种方式比较完美,但是稍微有一点不足,那就是只是生成小于RAND_MAX(32767)的随机数,《Accelerated C++》练习题中提供了一种改进的方式:
#include <cmath>#include <cstdlib>#include <iostream>#include <stdexcept>#include <limits.h>using namespace std;#define MY_RAND_MAX 32767int nrand(int n) { if (n <= 0) throw domain_error("Argument to nrand is out of range"); int r; if (n <= MY_RAND_MAX) { const int bucket_size = MY_RAND_MAX / n; do { int bucket = rand() / bucket_size; r = bucket; } while (r >= n); } else { const int bucket_size = ceil(n / MY_RAND_MAX); do { const int bucket = nrand(MY_RAND_MAX); const int remainder = nrand(bucket_size); r = (bucket - 1) * bucket_size + remainder; } while (r >= n); } return r;}int main() { int limit; while (cin >> limit) cout << nrand(limit) << endl; return 0;}
这种方式真的接近完美了,只是算法稍微复杂点。
0 0
- C/C++:随机数生成
- 随机数生成c++(转)
- objective-c 生成随机数
- C/C++生成随机数
- C语言生成随机数
- c生成随机数
- C随机数生成函数
- C语言生成随机数
- c 生成随机数
- C/C++随机数生成
- C/C++生成随机数
- C语言生成随机数
- C语言生成随机数
- C语言生成随机数
- c随机数生成
- c/c++生成随机数
- C/C++ 生成随机数
- C/C++生成随机数
- 学习《UNIX环境高级编程》笔记
- java中include动作和include指令的区别
- 开通了
- wpf 单例模式和异常处理
- BaseServlet的模板
- C++生成随机数
- 静态static
- 线段树的总结与习题acm杭电HDU1166
- Windows下创建定时计划任务
- 递归递推练习 J
- 进一步了解linux
- 动态规划--合唱队形
- Python中list、tuple、dict、set总结
- arggis sever 管理界面无法打开