C++ 随机数生成器 For 循环

标签 c++ random

所以,我在这里遇到一个小问题,因为 for 循环相当大。这个程序是模拟每步 100 步的随机游走 - 我想做的是让程序执行 100 万次这样的随机游走模拟(随机游走是通过嵌套的 for 循环基本上通过模拟翻转硬币来完成的,如下所示您可以在下面的代码中看到)并从每个随机游走中获取所得位移并将其打印到控制台窗口和指定的输出文件。

但是,我的代码似乎是从嵌套的 for 循环中添加 x 的每个最终值,然后将它们打印到控制台窗口(并保存到输出文件) - 我不想要这个,我只想要独立的网络每个 j 值(其范围从 1 到 1E6,由外部 for 循环指定)输出的每次随机游走的结果。

因此,任何帮助将不胜感激。另外,我非常感谢您不仅引用一些代码供我使用,而是向我解释我的程序逻辑出了问题以及原因。

提前致谢,我的代码如下!

#include <iostream>
#include <ctime>
#include <fstream>

using namespace std;

int main(void) {

    const unsigned IM = 1664525;
    const unsigned IC = 1013904223;

    const double zscale = 1.0/0xFFFFFFFF;      //Scaling factor for random double between 0 and 1
    unsigned iran = time(0);                        //Seeds the random-number generator from the system time
    const int nsteps(100);                          //Number of steps
    const int nwalks(1E6);

    int x(0);           // Variable to count step forward/back

    ofstream randout;
    randout.open("randomwalkdata2.txt");

    // Table headers for console window and output file

    cout << "Random Walk Number \t Resultant Displacement \n";
    randout << "Random Walk Number \t Resultant Displacement \n";

    for ( int j = 1 ; j <= nwalks ; j++ ) {

        for ( int i = 1 ; i <= nsteps ; i++ ) {

            // if-else statement to increment/decrement x based on RNG

            if ( zscale * double( iran = IM * iran + IC ) < 0.5 )   //RNG algorithm
                x++;
            else 
                x--;

        }

        cout << j << "\t" << x << endl;
        randout << j << "\t" << x << endl;

    }

    randout.close();

    return 1;

}

最佳答案

您忘记在每次随机游走后重新初始化 x。

    cout << j << "\t" << x << endl;
    randout << j << "\t" << x << endl;
    x=0;

应该可以解决问题。

关于C++ 随机数生成器 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19232409/

相关文章:

c++ - 在结构中引用另一个结构,其中第二个结构也引用第一个结构

c++ - 传递标准枚举值

C++ : SFINAE and random generator/engine

random - 生成非统一伪随机数的好库

javascript - 在 JavaScript RPG 中使用 "more random"RNG 有多重要?

c++ - CMake 对类的 undefined reference

c++ - 构造函数中对 (class)(type) 的调用不匹配

c++ - 如何让本地匿名 C++ 函数对象使用包含方法的参数?

javascript - 从不同的数组中选择随机字符串

C++ - 随机选择字符串而不选择它超过一次