2012-10-03 3 views
3

게임 코드 분리기 또는 기안자와 유사한 작은 C 프로그램을 만들고 있습니다. 지금까지 내 코드입니다. 현재로서는 "임의"코드를 생성하고 코드 배열을 인쇄합니다. 컴파일 할 때마다 2,2,6,3의 동일한 배열을 생성합니다. 누구든지 진정한 난수 생성기를 가질 수 있습니까?난수 생성기 도움말 난수 생성 안 함 - C

#include<stdio.h> 
#include<math.h> 
#include<stdlib.h> 
#include<time.h> 
#define CODELENGTH 4 
#define NUMSYMBOLS 6 
const int LOW = 1; 
const int HIGH = 6; 




void genCode (int MasterCode[]) 
{ 
int i=0; 
int k; 
while (i < 4){ 

MasterCode[i] =rand() %(HIGH-LOW+1)+LOW; 
    i++; 

}//end while loop. 
for (k = 0 ; k < 4; k++) { 
    printf("%d ", MasterCode[ k ]); 
} 

printf("\n"); 
    } 





void getGuess (int guess[]) 
{ 
int b[ 4 ]; 
int number = 0; 

printf("Please enter your list of 4 numbers between 1 and 6: "); 
int j; 
int k; 
for (j = 0 ; j < 4; j++) { 
    scanf("%d", &number); 
    b[ j ] = number; 
} 

printf("Your array has these values: "); 

for (k = 0 ; k < 4; k++) { 
    printf("%d ", b[ k ]); 
} 

printf("\n"); 
} 




int main (int argc, char **argv) 
{ 
int MasterCode[4]; 
genCode(MasterCode); 



} 
+2

가능한 복제본 [왜 난 항상 랜덤 번호의 동일한 시퀀스를 rand()와 함께 사용합니까?] (http://stackoverflow.com/questions/1108780/why-do-i-always-get-the-same) -sequence of-random-numbers-with-rand) – Blastfurnace

+1

요청하기 전에 찾으십시오. –

답변

7

rand()을 사용하기 전에 난수 생성기를 시드해야합니다. 이것은 보통 다음과 같이 이루어집니다 :

srand(time(NULL)); 

자세한 정보는 here입니다.

+0

감사합니다. C 참조 웹 사이트에서 rand 함수를 찾아 보니 문제가되었습니다. 감사합니다. –

0

내가 수행 한 작업은 원래 범위에서 사용했던 방정식을 제거하고 더 간단한 것으로 전환 한 다음 주 생성기를 추가했습니다.

#include<stdio.h> 
#include<math.h> 
#include<stdlib.h> 
#include<time.h> 
#define CODELENGTH 4 
#define NUMSYMBOLS 6 




void genCode (int MasterCode[]) 
{ 
int i=0; 
int k; 
while (i < 4){ 

MasterCode[i] =rand() %6 +1; 
    i++; 

}//end while loop. 
for (k = 0 ; k < 4; k++) { 
    printf("%d ", MasterCode[ k ]); 
} 

printf("\n"); 
} 





void getGuess (int guess[]) 
{ 
int b[ 4 ]; 
int number = 0; 

printf("Please enter your list of 4 numbers between 1 and 6: "); 
int j; 
int k; 
for (j = 0 ; j < 4; j++) { 
    scanf("%d", &number); 
    b[ j ] = number; 
} 

printf("Your array has these values: "); 

for (k = 0 ; k < 4; k++) { 
    printf("%d ", b[ k ]); 
} 

printf("\n"); 
} 




int main (int argc, char **argv) 
{ 
srand (time(NULL)); 
int MasterCode[4]; 
genCode(MasterCode); 



} 
1

정말 임의 생성기는 비쌉니다.
rand() 함수는 무작위로 보이지만 항상 동일하게 보이는 시퀀스를 생성합니다.

srand(time(NULL));
은 당신이 원하는 당신을 줄 것이다 가능성이 가장 높은마다 다를 수 있습니다 특정 값이 초기화됩니다 라인.
게임의 경우이 정도면 충분합니다. 그 이상으로 무작위 순서가 필요한 경우 키 입력, 마우스 이동 및 시간과 같은 사용자 입력을 기반으로 무언가를 생성 할 수 있습니다.
특수 하드웨어가 없어도 가능한 한 근접합니다.

+1

'srand (time (NULL))와 사용자 입력 사이에 암호 품질 의사 랜덤 생성기가 있습니다. http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator –