2017-04-16 246 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中有解释。你没有文档编程?