所以,我这里有一个小问题,有一个相当大的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;
应该做这个伎俩。