用C编写一个游戏
以下是一个简单的猜数字游戏的C代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int randomNumber, guess, attempts = 0;
// 生成一个随机数
srand(time(0));
randomNumber = rand() % 100 + 1;
printf("猜数字游戏!\n");
do {
printf("请输入一个1到100之间的数字:");
scanf("%d", &guess);
attempts++;
if (guess > randomNumber) {
printf("太大了!\n");
} else if (guess < randomNumber) {
printf("太小了!\n");
} else {
printf("恭喜你猜对了!你用了%d次尝试。\n", attempts);
}
} while (guess != randomNumber);
return 0;
}
这个程序会随机生成一个1到100之间的数字,并要求用户猜测这个数字是多少。用户每次猜测后,程序会告诉用户猜的数字是太大了还是太小了,直到用户猜对为止。程序会统计用户猜了多少次才猜对,并在最后输出出来
原文地址: https://www.cveoy.top/t/topic/ipgb 著作权归作者所有。请勿转载和采集!