猜数字的难点(例如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;
}
代码不唯一,可以试着用你的方法写一个。