Main.cpp和随机数生成器C++的一个函数
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,我们完全不知道该怎么做,也不知道该如何调用函数并从程序输出中为FNG的前1到10个调用和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();
}
}
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何仅为一个函数添加延迟
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 我需要将多个函数组合为一个函数
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 编写一个函数以使用 n 百分比的 CPU 使用率
- 将 N-arg 函数包装到另一个函数中
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- C++从另一个函数退出函数
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 视觉我希望一个函数在另一个函数C++中进行计算
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 在另一个函数 (c++) 中调用变量
- 如何在另一个函数中使用返回值作为参数?
- 如何包装一个函数以适应另一个函数的所需类型
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针