2017-04-16 3 views
0

나는 플레이어가 주사위 immediatly이기 든 지든 어떤 점없는 던질 때, 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()'의 호출은이를 수행해야합니다. 'again()'에서 호출하면 상황이 악화 될뿐입니다. 그래도 문제가 지속되면 질문을 편집하여 [mcve]를 제공하십시오. 정확히 무슨 일이 벌어 지는지 예상대로 설명하십시오. –

답변

2

두 번째로 srand을 호출하면 (again 함수에서) 난수 생성기를 이전 호출과 동일한 시드로 초기화 할 수 있습니다. time() 초 (대부분 C++ reference 참조) 이전에 생성 된 임의의 숫자 시퀀스를 다시 만들려는 경우가 아니면 난수 생성기를 다시 초기화하지 마십시오.

1

프로그램에서 이미 "()부터 srand를"다시,하지만 여전히 다시 srand()을 사용하기 때문이다

작동하지 사용하는 함수를 만들 수 있습니다.

프로그램 시작시 한 번만하십시오.

이것은 the cppreference documentation에서 설명합니다. 문서없이 프로그래밍하고 있습니까?

관련 문제