产生随机概率的c方法
2013-01-30 11:27
295 查看
问题
1>0~5% 2>5%~60% 3>60%~100%
用rand()产生概率
c实现
#include <stdio.h> #include <time.h> #include <stdlib.h> // before use this srand must be invoked. // probs must be ascending order and all of them should not greater than 1. // n is the number of probs. // returns the index of probs that the random result falls. int random_section(float probs[], int n) { double r = (float)rand()/RAND_MAX; int i; for (i = 0; i < n; i++) { if (r < probs[i]) { return i; } } return n; } int main() { srand((int)time(0)); float ps[] = {0.05, 0.6, 1}; int i; int count[4] = {0}; for (i = 0; i < 100000; i++) { int p = random_section(ps, 3); count[p]++; } for (i = 0; i < 4; i++) { printf("count[%d]=%d\n", i, count[i]); } return 0; }
相关文章推荐
- 一种快速可预制的随机数组产生方法
- 产生随机数组的方法
- 一种快速可预制的随机数组产生方法
- Javascript或jQuery方法产生任意随机整数
- 验证码中随机汉字的产生方法
- 计算随机抛1000次的骰子各个数字产生的概率。
- 直接选择排序的C++实现及随机数组的产生方法
- 产生唯一随机码的方法分析。
- php产生随机数的两种方法实例代码 输出随机IP
- jQuery中 Math.random()的用法方法>>产生任意随机整数
- mysql 随机字符的产生方法
- 实际中常用的一个随机数产生器(分类别概率随机) 推荐
- bat下产生指定范围随机数字的实现方法
- Java随机产生数组元素并无重复元素方法
- ArrayList中随机产生一个值的方法:
- Java基础知识强化80:Math类random()方法的小扩展(控制产生目的数字的概率)
- Java产生随机数和随机字母的方法
- 产生随机字符串的一种方法
- 产生随机数组的方法(后续更新)