C语言简单猜数字
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
// num1:随机数, num2:猜测数字, count:次数
//minn:最小范围, maxn:最大范围
int num1, num2, count, minn, maxn;
void guess() {
//时间种子
srand(time (NULL));
printf("\n请输入随机数范围,最大32767, 范围: 0 - ");
scanf("%d", &maxn);
//对最大值+1取模,确定范围
num1 = rand()%(maxn+1);
//初始化猜测次数
minn = count = 0;
printf("已随机产生一个0-%d的数字\n", maxn);
}
int main() {
//产生随机数
guess();
while(true) {
scanf("%d", &num2);
count++;
//对比并确定答案范围
if(num2 > num1) {
printf("你输入的%d太大了\n", num2);
maxn = num2 - 1;
}
if(num2 < num1) {
printf("你输入的%d太小了\n", num2);
minn = num2 + 1;
}
if(num2 == num1) {
printf("终于被你猜对了! 你总共猜了%d次\n", count);
printf("\n是否继续,继续输入1,其余退出: ");
int select;
scanf("%d", &select);
if(select == 1) {
guess();
continue;
}else {
break;
}
}
printf("答案的范围是[%d-%d]: ", minn, maxn);
}
return 0;
}