写一个猜数字的C语言代码
时间: 2024-06-04 14:11:37 浏览: 2
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int answer, guess, count = 0;
srand(time(NULL)); // 设置随机数种子
answer = rand() % 100 + 1; // 生成1-100之间的随机数
printf("猜数字游戏开始!\n");
do {
printf("请输入你猜测的数字(1-100):");
scanf("%d", &guess);
count++; // 记录猜测次数
if (guess > answer) {
printf("猜测的数字太大了,请重新输入!\n");
} else if (guess < answer) {
printf("猜测的数字太小了,请重新输入!\n");
}
} while (guess != answer);
printf("恭喜你,猜对了!你共猜测了%d次。\n", count);
return 0;
}
相关问题
写一段猜数字游戏 C语言代码
以下是一段简单的猜数字游戏的 C 语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int secret_num, guess, num_guesses = 0;
srand(time(NULL)); // 初始化随机数生成器
secret_num = rand() % 100 + 1; // 生成一个 1 到 100 之间的随机数
printf("我想了一个 1 到 100 之间的数字,你来猜猜看吧!\n");
do {
printf("你猜的数字是多少?");
scanf("%d", &guess);
num_guesses++;
if (guess < secret_num) {
printf("太小了,再试试吧!\n");
} else if (guess > secret_num) {
printf("太大了,再试试吧!\n");
} else {
printf("恭喜你,猜对了!你用了 %d 次猜中了答案!\n", num_guesses);
}
} while (guess != secret_num);
return 0;
}
用c语言写一个猜数字游戏的代码
好的,以下是用C语言写一个猜数字游戏的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int n, guess, count = 0;
srand(time(0));
n = rand() % 100 + 1; // 生成1-100的随机数
printf("我想了一个1-100之间的数字,你来猜猜是多少?\n");
do{
scanf("%d", &guess);
count++;
if(guess > n){
printf("猜大了,再试一试:\n");
}
else if(guess < n){
printf("猜小了,再试一试:\n");
}
else{
printf("恭喜你,猜对了!你用了%d次机会\n", count);
break;
}
} while(1);
return 0;
}
```
请注意,这只是一个简单的猜数字游戏代码示例,您可以根据需要进行适当修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)