猜数游戏:编写C语言程序要求学生用随机函数产生一个数,判断用户是否猜对,如果猜错了,则提示偏大还是偏小,记录用户猜数所用的次数。
时间: 2024-02-21 15:56:47 浏览: 79
好的,这是一个猜数游戏的C语言程序的示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int num, guess, count = 0;
srand(time(NULL)); // 设置随机种子
num = rand() % 100 + 1; // 生成1~100之间的随机数
do {
printf("请猜一个1~100之间的整数:");
scanf("%d", &guess);
count++;
if (guess > num) {
printf("偏大了!\n");
} else if (guess < num) {
printf("偏小了!\n");
} else {
printf("恭喜你,猜对了!\n");
printf("你一共猜了%d次。\n", count);
}
} while (guess != num);
return 0;
}
```
这个程序先用 `srand()` 函数设置随机数种子,然后用 `rand()` 函数生成一个1~100之间的随机数。接着进入一个循环,让用户输入猜的数,并且记录猜数的次数。如果猜对了,输出恭喜信息和猜数次数;否则,输出偏大或偏小的提示信息。直到用户猜对为止,循环结束。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)