题干为I have selected a character between A and Z Try to guess the character selected by me ! What is your guess ?
然后输入一个字母,会响应下面三句之一1. Great! Your guess is right! 2. Way ahead! Please try again. 3. Way behind! Please try again.
如果输入错误则程序循环,知道玩家找出正确的(用binary search)
#include <stdio.h>
int main()
{
char target ='D';
while(true)
{
char min = 'A';
char max = 'Z';//初始范围
int count = 0;//猜测次数
int guess = 0;
printf("please input a character between %c and %c\n",min,max);
fflush(stdin);//清空输入缓存,以便不影响后面输入的数。比如你逐个输入字符,他帮你缓冲掉你每输入一个字符后面所敲的回车键。否则回车也会被当成字符保存进去。
scanf("%c",&guess); // 获取猜测的数字
++count;
if(target == guess) //猜中
{
printf("YOU WIN!\nyou have guessed %d times in total.\n",count);
break;
}
else if(target > guess) //目标比猜的数字大
{
min = guess;
printf("the target is larger than %c\n",guess);
}
else //目标比猜的数字小
{
max = guess;
printf("the target is less than %c\n",guess);
}
}
return 0;
}
代码如上,万望采纳。
#include <time.h>
#include <stdlib.h>
void main()
{
printf("I have selected a character between A and Z Try to guess the character selected by me ! What is your guess ?");
srand((unsigned)time(NULL));//选取种子文件
char c = rand()%26 + 'A';
while(true)
{
char a;
scanf("%c",&a);
getchar();
if(a < c)
printf("Way ahead! Please try again.");
else if(a > c)
printf("Way behind! Please try again");
else
{
printf("Great! Your guess is right!");
break;
}
printf("\nguess again:");
}
}
您的问题已经有小伙伴解答了,请点击【采纳】按钮,采纳帮您提供解决思路的答案,给回答的人一些鼓励哦~~
ps:开通问答VIP,享受5次/月 有问必答服务,了解详情↓↓↓
【电脑端】戳>>> https://vip.csdn.net/askvip?utm_source=1146287632
【APP 】 戳>>> https://mall.csdn.net/item/52471?utm_source=1146287632