2013-10-07 111 views
2

所以,我有一個小問題,這裏有一個相當大的for循環。這個程序是模擬每步100步的隨機遊走 - 我想要做的是讓程序執行100萬次這些隨機遊走模擬(隨機遊走基本上是通過模擬硬幣翻轉來嵌套for循環來完成的,就像你可以在下面的代碼中看到),並從每個這些隨機散步中產生位移,並將它們打印到控制檯窗口和指定的輸出文件。C++隨機數發生器的循環

但是,我的代碼似乎是從嵌套for循環添加每個最終的x值,然後將它們打印到控制檯窗口(並保存到輸出文件) - 我不想要這個,我只想單獨每個隨機遊走的淨結果對於j的每個值(其範圍從1到1E6,由外循環指定)輸出。

因此,任何幫助將不勝感激。另外,我非常感謝您不要僅僅引用一些代碼來代替,而是向我解釋程序邏輯出錯的原因以及原因。

在此先感謝,我的代碼在下面!

#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; 

} 
+1

您需要在第一個循環的開頭將x重置爲零 – pippin1289

回答

5

你忘了在每次隨機遊走後重新初始化x。

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

應該這樣做。

+0

Aha!非常感謝,我不確定我是如何錯過的 - 現在看起來很明顯。 –