2013-08-08 1 views
3

여기 간단한 문제가 있지만 해결 방법이 없습니다! 숫자 생성기를 만들려고 노력하고 있지만 1-6에서 임의의 숫자를 선택하기를 원합니다. 0이 없습니다! 이 질문은 DUP를 표시했지만이 C++하지 C 있기 때문에 안 :rand() number from 1-6

srand(static_cast<unsigned int>(time(0))); 
int dice = rand()%6; 
+0

그냥 '주사위'에 1을 더하십시오. – Saksham

+3

Near-duplicate : http://stackoverflow.com/q/2999075/179910 –

+1

'rand()/RAND_MAX * (max_n - min_n) + min_n; 사용' –

답변

9

rand() % 6의 범위 0..5에 숫자를 제공합니다. 하나를 추가하여 1..6 범위를 가져옵니다.

4

은 거의 그것을 가지고 :

int dice = rand()%6 + 1;

+0

우수, 감사합니다! – ssj3goku878

9

C++ (11)는 다소 단순하고 덜 오류가 발생하기 쉬운 당신은 또한 std::uniform_int_distribution이 옵션 (참조 rand() Considered Harmful presentationslides) 인 경우 :

#include <iostream> 
#include <random> 

int main() 
{ 
    std::random_device rd; 

    std::mt19937 e2(rd()); 

    std::uniform_int_distribution<> dist(1, 6); 

    for(int i = 0 ; i < 10; ++i) 
    { 
     std::cout << dist(e2) << std::endl ; 
    } 

    return 0 ; 
} 

이 이전 스레드 Why do people say there is modulo bias when using a random number generator?은 chris가 그의 의견에서 지적한 모듈러스 바이어스를 명확하게 설명합니다.

+0

그리고 modulus 바이어스와 결합 된'rand()'생성기보다 훨씬 낫습니다. – chris

+0

@chris 모듈로 바이어스를 설명하는 링크 추가 –