2014-05-10 2 views
1

아래 코드를 C++로 wrotte했지만 한 가지 문제가 있습니다. 항상 같은 코드를 사용하는 임의의 숫자 .. !! 여기 내 코드와 스크린 샷입니다 :C++의 무작위 int

#include <iostream> 
using namespace std; 

int main() { 
    cout << "I got a number in my mind... can you guess it?" << endl; 
    int random; 
    random = rand() % 20 + 1; 

    cout << random << endl; 
    system("pause"); 
    return 0; 
} 

스크린 샷 : http://tinyurl.com/n49hn3j 당신이 srand 기능을 사용하여 임의을 초기화하기 (씨앗) 할 필요가

+2

프로그램 시작 부분에 난수 생성기를 시드해야합니다. cstdlib 헤더를 포함하고 srand (time (0))를 추가하십시오. 귀하의 주요 기능의 시작 부분에. –

+0

@AbhishekBansal +1, 시도 srand (시간 (0)); –

+0

@JossefHarush가 편집되었습니다. –

답변

0

. 당신은 당신이 마지막으로했던 같은 초에 시작하지 않는 경우 more info

#include <iostream> 
#include <stdlib.h>  /* srand, rand */ 
#include <time.h>  /* time */ 
using namespace std; 

int main() { 

    // Seed the random number generator 
    srand(time(0)); 

    cout << "I got a number in my mind... can you guess it?" << endl; 

    int random; 
    random = rand() % 20 + 1; 

    cout << random << endl; 
    system("pause"); 
    return 0; 
} 
6

srand(time(0))은 새로운 난수를 생성합니다. 또한 issues with using rand() % 20이 있습니다.

#include <iostream> 
#include <random> 
int main(){ 
    std::random_device rd; 
    std::mt19937 mt(rd()); 
    std::uniform_int_distribution<int> dist(1, 20); 
    std::cout << dist(mt); 
} 
+1

전체'std' 네임 스페이스를 가져 오는 것이 단지 작은 부분 만 사용하는 경우 항상 좋은 생각은 아닙니다. 단지 $ 0.02 –

+0

@ IosifM입니다. 참된. 비록 함수와 코드 예제 안에 있기 때문에 빠져 나갈 수는 있지만 물론 올바르게 수행되어야합니다. 나는 그것을 고쳤다. – nwp

+0

+1을 사용하여 C + + 11 버전을 사용하고 rand()를 엉망으로 전파하지 마십시오 – dutt

0

대신이 시도 :

#include <ctime> //for current time 
#include <cstdlib> //for srand 
    srand (unsigned(time(0))); //use this seed 

이것은 또한 당신의 임의에 대한 작동이 옳은 일을 할 것입니다.