【发布时间】:2009-03-05 02:06:06
【问题描述】:
我有以下 C++ 代码试图生成 一个随机数。 idea 是我们给出了一些速率“x”和运行次数; 我们希望它会产生与 (x * number of runs times) 一样多的数字。
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <time.h>
using namespace std;
int main () {
// Initialize Random Seed
srand (time(NULL));
string line;
double SubsRate = 0.003;
double nofRuns = 1000000;
for (unsigned i=0; i < nofRuns ; i++) {
int toSub = rand() % 1000 + 1;
if (toSub == (SubsRate * 1000)) {
cout << toSub << " Sub" << endl;
}
}
return 0;
}
因此,如果我们使用此命令运行上述代码 K 次:
$ a=0 ; while test $a -lt 10 ; do ./MyCode | wc -l ; a=`expr $a + 1` ; done
我们预计它会在 1M 次运行中生成多达约 3000 次的数字“3”。但 一些我上面的代码如何只生成数字“3”多达 900 ~ 1000 次。
如何改进我上面的代码?
【问题讨论】: