number_guess.c

Download
c 53 lines 1.3 KB
 1// number_guess.c
 2// 숫자 λ§žμΆ”κΈ° κ²Œμž„
 3
 4#include <stdio.h>
 5#include <stdlib.h>
 6#include <time.h>
 7
 8int main(void) {
 9    int secret, guess, attempts;
10    int min = 1, max = 100;
11
12    // λ‚œμˆ˜ μ‹œλ“œ μ΄ˆκΈ°ν™”
13    srand(time(NULL));
14
15    printf("=== 숫자 λ§žμΆ”κΈ° κ²Œμž„ ===\n");
16    printf("1λΆ€ν„° 100 μ‚¬μ΄μ˜ 숫자λ₯Ό λ§žμΆ°λ³΄μ„Έμš”!\n\n");
17
18    // 1-100 사이 랜덀 숫자 생성
19    secret = rand() % 100 + 1;
20    attempts = 0;
21
22    while (1) {
23        printf("숫자λ₯Ό μž…λ ₯ν•˜μ„Έμš” (%d ~ %d): ", min, max);
24
25        if (scanf("%d", &guess) != 1) {
26            printf("μ˜¬λ°”λ₯Έ 숫자λ₯Ό μž…λ ₯ν•˜μ„Έμš”.\n");
27            while (getchar() != '\n');  // μž…λ ₯ 버퍼 λΉ„μš°κΈ°
28            continue;
29        }
30
31        attempts++;
32
33        if (guess < min || guess > max) {
34            printf("λ²”μœ„ λ‚΄μ˜ 숫자λ₯Ό μž…λ ₯ν•˜μ„Έμš”!\n");
35            continue;
36        }
37
38        if (guess == secret) {
39            printf("\nμ •λ‹΅μž…λ‹ˆλ‹€! πŸŽ‰\n");
40            printf("%d번 λ§Œμ— λ§žμΆ”μ…¨μŠ΅λ‹ˆλ‹€.\n", attempts);
41            break;
42        } else if (guess < secret) {
43            printf("더 큰 μˆ«μžμž…λ‹ˆλ‹€.\n");
44            if (guess > min) min = guess + 1;
45        } else {
46            printf("더 μž‘μ€ μˆ«μžμž…λ‹ˆλ‹€.\n");
47            if (guess < max) max = guess - 1;
48        }
49    }
50
51    return 0;
52}