2015-03-02 46 views
0

在這裏,我擲骰子並將結果存儲在一個映射中(int表示發生數字,頻率較長,即發生/試驗)。這是一個典型的輸出:生成隨機骰子卷和測量結果的頻率

Please select the number of trials: 
100 
Dice roll of 1 has 327% outcomes 
Dice roll of 2 has 16722170% outcomes 
Dice roll of 3 has 327% outcomes 
Dice roll of 4 has 14872209% outcomes 
Dice roll of 5 has 327% outcomes 
Dice roll of 6 has 16724069% outcomes 

正如你所看到的頻率都是discombobulated。他們應該總計爲1.我試圖搞亂精度,但這似乎不是我的問題的根源。代碼很簡單。任何人都可以查明我的問題?親切的問候。

#include <boost/random.hpp> 
#include <iostream> 
#include <ctime>    
#include <boost/Random/detail/const_mod.hpp> // LCG class 
#include <map> 

using namespace std; 


int main() 
{ 
    //throwind dice 
    //Mersenne Twister 
    boost::random::mt19937 myRng; 

    //set the seed 
    myRng.seed(static_cast<boost::uint32_t> (time(0))); 

    //uniform in range [1,6] 
    boost::random::uniform_int_distribution<int> six(1,6); 

    map<int, long> statistics; //structure to hold outcome + frequencies 
    int outcome; //current outcome 

    cout << "Please select the number of trials:" << endl; 
    int trials; //# of trials 
    cin >> trials; 
    int oc1; int oc2; int oc3; int oc4; int oc5; int oc6; //outcomes 
    for (int i = 0; i < trials; ++i) 
    { 
     outcome = six(myRng); 

     if (outcome == 1) 
     { 
      oc1++; 
      statistics[1] = oc1/trials; 
     } 

     if (outcome == 2) 
     { 
      oc2++; 
      statistics[2] = oc2/trials; 
     } 

     if (outcome == 3) 
     { 
      oc3++; 
      statistics[3] = oc3/trials; 
     } 

     if (outcome == 4) 
     { 
      oc4++; 
      statistics[4] = oc4/trials; 
     } 

     if (outcome == 5) 
     { 
      oc5++; 
      statistics[5] = oc5/trials; 
     } 

     if (outcome == 6) 
     { 
      oc6++; 
      statistics[6] = oc6/trials; 
     } 
    } 

    for (int j = 1; j <= 6; ++j) 
     cout << "Dice roll of " << j << " has " << statistics[j] << "% outcomes" << endl; 

    return 0; 
} 
+0

你正在初始化結果變量嗎? ('oc1'到'oc6') – 2015-03-02 04:46:14

+0

我試過了「int outcome = six(myRng);」但沒有成功。我也將oc1,oc2,oc3等初始化爲0,但是這給了我直接的「0%結果」。 – kits 2015-03-02 04:48:34

+0

J-Kubik發現你的問題。整數的默認初始化是一個隨機數(通常是內存中已有的內存)。只需將所有'oc'變量設置爲0並且您應該沒有問題 – Alejandro 2015-03-02 04:50:29

回答

1

簡單,你沒有初始化oc1, oc2,

但你的代碼可以使用一些簡化:

int oc[6] = {}; 
for (int i = 0; i < trials; ++i) 
{ 
    outcome = six(myRng); 
    oc[outcome-1]++; 
    statistics[outcome] = oc[outcome-1]/trials; 
} 

這不僅初始化值,但可以縮短環路。

但是,正如評論所建議的,如果你想要浮點數,你需要改變你的類型來允許浮點值,而不是整數。