5、修改清单8.4中的猜测程序,使其使用更智能的猜测策略。例如,程序最初猜50,让其询问用户该猜测值是大,小还是正确。如果猜测值小,则令下一次的猜测值为50和100的中值,也就是75。如果75大,则下一次猜测75和50的中值,等等。
#include <stdio.h>
#include <stdlib.h>
#include<ctype.h>
int main()
{
int min = 1;
int guess= 50;
int max = 100;
char ch;
printf("pick an integer from 1 to 100.I will ");
printf("try to guess it.\nRespond with a y if my");
printf(" guess is right and with a s if it is ");
printf("small and with a b if is big.\n");
printf("Uh...is your nubmer %d\n",guess);
while((ch=getchar())!='y')
{
if(ch=='s')
{
min=guess;
guess=(max+min)/2;
printf("well,then is %d\n",guess);
}
if(ch=='b')
{
max=guess;
guess=(max+min)/2;
printf("well,then is %d\n",guess);
}
else if(getchar()!='\n')
printf("sorry,I undestand y,s or b.\n");
while(getchar()!='\n');
}
printf("I knew I could do it.\n");
return 0;
}
2、编写一个程序,把输入作为字符流读取,指导遇到EOF。令该程序打印每个输入字符及其ASCII编码的十进制值。注意在ASCII序列中空格字符前面的字符是非打印字符,要特殊处理这些字符。如果非打印字符是换行符或制表符,则分别打印\n或\t。否则,使用控制字符符号。例如,ASCII的1是Ctrl+A,可以显示为^A。注意A的ASCII是Ctrl+A的值加上64,,对其他非打印字符也保持相似的关系。除去每次遇到一个换行符时开始新的一行之外,每行打印10对值。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
int count=0;
printf("please enter words\n");
while((ch=getchar())!=EOF)
{
if(ch=='\n')
printf("\\n|%d ",ch,ch);
else if(ch=='\t')
printf("\\t|%d ",ch,ch);
else if(ch>=0&&ch<' ')
printf("^%c|%d ",ch+64,ch+64);
else
printf("%c|%d ",ch,ch);
count++;
if(count%10==0)
printf("\n");
}
return 0;
}