C_C++

(C언어) 주사위 시뮬레이션 (dice simulation)

고니자니 2024. 1. 25. 12:35
반응형

C 언어에서  1부터 6까지의 숫자가 나오는 주사위를 1000번 던져서 나오는 시뮬레이션을 프로그램을 만들었습니다.

rand() 함수를 사용해서 실행할 때마다 매번 다른 결과를 나타냅니다.

파이썬 코드가 필요하면 하단에 링크가 있습니다.

 

C언어에서는 그래프 표현이 복잡해서 텍스트로 결과를 표시했습니다.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N   1000

void throwDie(int numThrows, int results[]) {
    for (int i = 0; i < numThrows; i++) {
        results[i] = (rand() % 6) + 1;
    }
}

void textGraph(int numThrows, int results[]) {
    printf("Die Face   Frequency\n");
    for (int face = 1; face <= 6; face++) {
        int count = 0;
        for (int i = 0; i < numThrows; i++) {
            if (results[i] == face) {
                count++;
            }
        }
        printf("%8d   %9d\n", face, count);
    }
}

int main() {
    srand(time(NULL)); // Seed the random number generator

    int results[N];

    // Simulate throwing a die 1000 times
    throwDie(N, results);

    // Display the results as a bar graph
    textGraph(N, results);  // 

    return 0;
}

주사위 시뮬레이션, 첫 번째 실행 결과

 

주사위 시뮬레이션, 두 번째 실행 결과

 

 


파이썬 코드:

https://coding-abc.tistory.com/271

 

(파이썬) 주사위 시뮬레이션 (dice simulation)

파이썬으로 1부터 6까지의 숫자가 나오는 주사위를 1000번 던져서 나오는 수를 막대 그래프로 그렸습니다. 파이썬의 random 모듈과 그래프는 "matplotlib" 모듈을 사용했습니다. 여기서는 주피터 노트

coding-abc.kr

 

728x90
반응형