Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C เกมทายตัวเลข (Guess the Number)

ปัญหา

โปรแกรมมีตัวเลขคงที่อยู่แล้ว ผู้ใช้ต้องทายเลขนั้น โดยให้คำใบ้ทุกครั้งที่ทาย

วิธีแก้ปัญหา

ตรรกะการทายเลข:

do {
    if(num == guess) {
        flag = 0;
    } else if(guess < num) {
        flag = 1;
        printf("Your guess is lower than the number\n");
        count++;
    } else {
        flag = 1;
        printf("Your guess is greater than the number\n");
        count++;
    }
    if(flag == 1) {
        printf("sorry wrong enter! once again try it\n");
        scanf("%d", &guess);
    }
} while(flag);

ตัวอย่างโค้ด

#include <stdio.h>

int main() {
    int i, num = 64, flag = 1, guess, count = 0;
    printf("guess the number randomly here are some clues later\n");
    scanf("%d", &guess);
    do {
        if(num == guess) {
            flag = 0;
        } else if(guess < num) {
            flag = 1;
            printf("Your guess is lower than the number\n");
            count++;
        } else {
            flag = 1;
            printf("Your guess is greater than the number\n");
            count++;
        }
        if(flag == 1) {
            printf("sorry wrong enter! once again try it\n");
            scanf("%d", &guess);
        }
    } while(flag);
    printf("Congratulations! You guessed the correct number %d\n", num);
    printf("Total number of trails you attempted for guessing is: %d\n", count);
    return 0;
}

ผลลัพธ์

guess the number randomly here are some clues later
45
Your guess is lower than the number
sorry wrong enter! once again try it
60
Your guess is lower than the number
sorry wrong enter! once again try it
70
Your guess is greater than the number
sorry wrong enter! once again try it
65
Your guess is greater than the number
sorry wrong enter! once again try it
62
Your guess is lower than the number
sorry wrong enter! once again try it
64
Congratulations! You guessed the correct number 64
Total number of trails you attempted for guessing is: 5