2017-04-11 31 views
0

因此,我編寫了一個代碼來模擬遊戲中的賭博機器。基本上,你按下一個按鈕,你有機會加倍你的積分。另一方面,如果你失敗了,你必須重新開始。示例運行可能是:「Double or Nothing」賭博機器代碼無法達到15個組合

Start of run 1: 
0 
1 
2 
Start of run 2: 
0 
1 
Start of run 3: 
0 
Start of run 4: 
0 
1 
2 

它工作正常。我讓代碼做了一定的運行(由用戶輸入'n'確定)並輸出在所有這些運行中達到的最大組合。它還會告訴我們什麼時候最高的組合超過了。

問題是,經過一定量的運行後,無論出於何種原因,最高組合不能超過15個。從字面上看,我每次輸入1000萬或更多(它給出15個)。它看起來不正確,因爲它根本不匹配概率。

我種下它的方式有什麼問題嗎? ?

#include <iostream> 
#include <stdlib.h> 
//#include "stdafx.h" 
#include<ctime> 

using namespace std; 

int main() { 

    int n = 1; 

    srand(time(0)); 
    while (n > 0) { 
     cin >> n; 

     int highestCombo = 0; 
     for (int i = 0; i < n; i++) { 
      int combo = 0; 
      while (true) { 
       int r = (rand() % 2) + 1; 

       if (r == 1) { 
        combo++; 
       } 
       else if (r == 2) { 
        if (combo > highestCombo) { 
         highestCombo = combo; 
         cout << combo << " at #" << i << endl; 
        } 
        combo = 0; 
        break; 
       } 
      } 
     } 
     cout << "Highest Combo: " << highestCombo << endl; 
    } 
} 

編輯:如此看來,它可能只是我的IDE奇怪我使用開發,C++,因爲我只是想快點寫嗎?但是,cpp.sh必須高於15進入。 20s。

+2

請的代碼中的相關行添加到你** **問題。 – datell

+0

http://en.cppreference.com/w/cpp/numeric/random – Raxvan

+0

所以基本上你要做的就是等待rand()返回一個超過15次的奇數。 。? – Rogus

回答

1

正確答案接縫來自tobi303。我爲你測試了他的解決方案,並使用「< random」代替,效果更佳。

#include <iostream> 
#include <stdlib.h> 
//#include "stdafx.h" 
#include<ctime> 

using namespace std; 

int main() { 

int n = 1; 

//srand(time(NULL)); 

std::mt19937 rng; 
rng.seed(std::random_device()()); 
std::uniform_int_distribution<std::mt19937::result_type> rand(1,2); 
while (n > 0) { 
    cin >> n; 

    int highestCombo = 0; 
    for (int i = 0; i < n; i++) { 
     int combo = 0; 
     while (true) { 
      //int r = (rand() % 2); 
      int r = rand(rng); 

      if (r == 1) { 
       combo++; 
      } 
      else if (r == 2) { 
       if (combo > highestCombo) { 
        highestCombo = combo; 
        cout << combo << " at #" << i << endl; 
       } 
       combo = 0; 
       break; 
      } 
     } 
     if(i == n - 1) 
     { 
      cout << " i " << i << endl; 
     } 
    } 

    cout << "Highest Combo: " << highestCombo << endl; 
} 

}