Main.cpp和随机数生成器C++的一个函数

Main.cpp and a Function for Random number Generator C++

本文关键字:一个 函数 cpp 随机数生成器 C++ Main      更新时间:2023-10-16

嗨,我是这里的新手,我希望能在这里做好。上学期,我们与随机数生成器打交道,我和我的朋友想出了一个简单的程序(如下),它很有效:

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();
   }
}