C言語で数字当てゲームをどう実装するのか。
C言語での簡単な数字当てゲームの実装例を以下に示します。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int target, guess, attempts = 0;
// 生成随机数作为目标数字
srand(time(0));
target = rand() % 100 + 1;
printf("欢迎来到猜数字小游戏!\n");
printf("游戏规则:请猜一个1到100之间的数字\n");
do {
printf("请输入你的猜测:");
scanf("%d", &guess);
attempts++;
if (guess < target) {
printf("你猜的数字太小了,请再试一次。\n");
} else if (guess > target) {
printf("你猜的数字太大了,请再试一次。\n");
} else {
printf("恭喜你猜对了!你用了 %d 次猜对了数字 %d。\n", attempts, target);
}
} while (guess != target);
return 0;
}
このコードは、1から100の間のランダムな数字を生成してそれを目標数字とし、プレーヤーに数字を推測させ、その推測に応じたヒントを与え、プレーヤーが正解するまで続けます。ゲーム中にプレーヤーの推測回数をカウントします。