2017-04-16 106 views
0

我要創建一個使用C++產生兩個不同的隨機數

在「胡扯」簡單的「骰子」遊戲中,當玩家扔骰子是不是有些點立刻輸贏,他們需要拋出再次

但我不能改變骰子點數,當它需要拋出再次

#include <iostream> 
#include <cstdlib> 
#include <ctime> 

using namespace std; 

void again(int first) { 
    srand(time(NULL)); 
    int dice11, dice22, total2; 
    do { 
     dice11 = (rand() % 6 + 1); 
     dice22 = (rand() % 6 + 1); 
     total2 = dice11 + dice22; 
     cout << "Player throw " << total2 << endl; 
     if (total2 == first) 
      cout << "Player Win" << endl; 
     if (total2 == 7) 
      cout << "Player Lose" << endl; 
    } while (total2 != first); 

} 



int main() { 
    srand(time(NULL)); 
    int dice1, dice2,total; 
     dice1 = (rand() % 6 + 1); 
     dice2 = (rand() % 6 + 1); 
     total = dice1 + dice2; 

     if (total == 7 || total == 11) 
      cout << "Player throw " << total << " Player Win" << endl; 
     else 
      if (total == 2 || total == 8 || total == 12) 
       cout << "Player throw " << total << " Player Lose" << endl; 
      else 
      { 
       cout << "Player throw " << total << endl; 
       again(total); 
      } 


    system("pause"); 
    return 0; 
} 

在程序中,我已經創建使用「函數srand()」函數再次,但它仍然無法正常工作

+2

你應該在你的程序中調用'srand()'一次 - 'main()'中的調用應該這樣做。再次調用它()會讓事情變得更糟。如果您仍然有問題,請編輯您的問題以提供[mcve] - 包括準確解釋發生的事情與您的期望。 –

回答

2

你的第二個電話srand(函數again)可能很好地將隨機數發生器初始化爲與前一次調用相同的種子。 time()計數秒(主要參見C++ reference)。不要重新初始化隨機數發生器 - 除非你想重新創建一個先前產生的隨機數序列。

1

在程序中,我已經創建使用的功能「srand()函數」了,但它仍然無法正常工作

那是因爲你再次使用srand()

在程序開始時只做一次。

這在the cppreference documentation中有解釋。你沒有文檔編程?