[英]Main.cpp and a Function for Random number Generator C++
嗨,我是这里的新手,希望能在这里休息。 上学期,我们处理了随机数生成器我和我的朋友,我们能够提出一个简单的程序(如下所示),该程序有效:
using namespace std;
int randomG() {
int GER(0);
GER=rand();
GER %= 10;
GER++;
return(GER);
}
int main() {
srand((unsigned)time(NULL));
for(int i = 0; i != 100; i++) {
cout << randomG();
}
}
现在,这个学期我们没有花太多时间就得到了这个。 基本上,他希望我们用main.cpp实现多次调用函数FNC的随机数生成器,以测试程序,我们需要使用state = 1作为初始值。 从主程序调用FNC。 拨打10000次后:状态应等于399268537(此处不表示他的意思)
以下是我们的起点:
double rand (void) {
const long a=48271 //multiplier
const long b=2147483647 //modulus
const long c=b/a //questient
const long r=b % a //remainder
static long state =1;
long t = a* (state % c) - r * (state/c);
if(t >0)
state=t;
else
state = t+b;
return ((double) state / b);
}
对于main.cpp,我们完全不知道该怎么做,我们不知道如何调用该函数,以及如何从程序输出中为前1到10次调用以及F991到9991至10000次调用提供一个表。 我们不能再前进了。 对于像我们这样的大二学生,这是完全混乱的。 任何帮助将不胜感激
int main() {
srand((unsigned)time(NULL));
int // we lost on what we should put in our main
在你们的帮助之后,以下是我的代码,但仍然无法编译我在这里缺少的内容?
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
double seed(long state) {
g_state = state;
}
double rand(void) {
const long a = 48271;
const long b = 2147483647;
const long c = b / a;
const long r = b % a;
long t = a* (g_state % c) - r * (g_state / c);
if (t > 0)
g_state = t;
else
g_state = t + b;
return ((double)g_state / b);
}
int main() {
std::vector<double> results;
for (int i = 1; i <= 10000; ++i) {
double number = rand();
if (i <= 10 || i >= 9991)
results.push_back(number);
}
state
是你在这里的种子。 您使用1对其进行初始化。在10000次调用之后,它将是399268537
。 他给了您那个价值来检查您的实现。
int main()
{
for(int i = 0; i < 10000; ++i)
{
rand();
}
}
如果在此外观之后再次调用rand()
,然后进入该函数并检查state
的值,则会看到它是399268537。
我的代码可以重构为看起来更像srand()
和rand()
:
double seed(long state)
{
g_state = state;
}
double rand(void)
{
const long a = 48271;
const long b = 2147483647;
const long c = b / a;
const long r = b % a;
long t = a* (g_state % c) - r * (g_state / c);
if(t > 0)
g_state = t;
else
g_state = t + b;
return ((double)g_state / b);
}
int main()
{
seed(1);
for(int i = 0; i < 10000; ++i)
{
rand();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.