猜数字的难点(例如1到100)
- 导入 #include <stdlib.h> #include <time.h>这两个库
- 随机产生一个数代码 srand(time(0)); int rand_number=rand();
- 对产生的随机数取余即 int rand_number=rand()%100+1;不加1的话产生的数字是0到99
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//随机猜1-100之间的数字
int main(){
srand(time(0));
int rand_number=rand()%100+1;//产生一个1到100的随机数,包括1和100
int count=0;//计数
int a=0;
printf("我已经想好了一个1到100之间的数。\n");
do{
printf("请猜猜这个1到100之间的数是多少:");
scanf("%d",&a);//输入你猜的数字
count++;
if(a>rand_number){//判断猜的数字大小
printf("你猜的数大了。");
} else if(a<rand_number){
printf("你猜的数小了。");
}
}while(a!=rand_number);
printf("太好了,你用了%d次就猜到了答案。\n",count);
return 0;
}
代码不唯一,可以试着用你的方法写一个。
这篇博客介绍了如何使用C语言实现一个猜数字游戏,游戏中电脑随机生成1到100之间的数字,用户通过输入猜测并得到反馈,直到猜中为止。代码中包含了随机数生成、用户输入处理和循环条件判断等核心部分。
1万+

被折叠的 条评论
为什么被折叠?



