2016-06-05 2 views
-2

작은 프로그램의 경우 실행 중인데 rand() 함수를 사용하여 23 개의 정수 배열에 숫자를 제공하고 있습니다. 코드를 실행할 때마다 배열에서 이전에 사용되었던 동일한 숫자가 다시 사용되므로 반복마다 각기 다른 결과를 얻지는 않습니다. 이 문제를 어떻게 해결할 수 있습니까?코드를 실행할 때마다 rand() 배열이 변경되지 않습니다.

편집 : 코드는 생일의 역설을 실험 한 것입니다. 이 역설에 따르면 23 명으로 구성된 방에서 다른 사람과 생일을 나눌 수있는 기회는 50 %이지만 자연스럽게 대부분의 사람들은 그보다 작다고 생각합니다.

#include "stdio.h" 
#include "stdlib.h" 

#define interations 10 //number of repitition in the code for a more accurate percentage 
#define numppl 23 //number of people 

int main() 
{ 
    int inv; 
    float percent = 0, sum = 0; 
    int i, j, k; 
    int seq[numppl]; 

    for (inv = 0; inv < interations; inv++) 
    { 
     for (i = 0; i < numppl; i++) { 
      seq[i] = rand() % 365; //creates a random array of 'numppl' integers every iteration 
     } 

     for (j = 0; j < numppl; j++) 
     { 
      for (k = j + 1; k < numppl; k++) 
      { 
       if (seq[j] == seq[k]) //if any two number in the array match each other, increment sum by 1 
        sum++; 
      } 
     } 
    } 

    percent = (sum/interations) * 100; //divide the amount of arrays with numbers that match with the number of total arrays generated for a percentage 

    printf("Chance of two people sharing the same birthday is %f percent", percent); 
} 

각각의 반복은 임의의 숫자의 다른 배열입니다,하지만 난 다시 코드를 실행하면, 배열은 이전과 동일합니다, 그래서 rand()의 예상 behavoiur입니다 같은 비율

+1

''srand'를 찾으십시오. –

+4

이 작업을 수행하기 위해 작성한 코드를 표시해야합니다. 우리는 당신이 한 일을 알지 못하면 당신을 도울 수 없습니다. – Sterls

답변

1

를 얻을 . 난수 생성기에 srand()을 입력해야합니다.

관련 문제