书看完,能看懂了,不过写还差点,这不,碰到个题,现在明白了,发个贴子庆祝下
程序代码:
#include<stdio.h> #define N 5 void main(){ int a[N],k,z,t,w,i,num; char c; printf("enter date:\n"); scanf("%d",&a[0]); for(i=1;i<N;){ scanf("%d",&a[i]); if(a[i]<a[i-1]) printf("enter this date again:\n"); else i++; } for(i=0;i<N;i++) printf("%d ",a[i]); printf("\n"); while(i){ k=1; i=1; printf("input number to look for: "); scanf("%d",&num); if((num>a[N-1])||(num<a[0])) i=0; else{ t=0; w=N-1; while(k){ z=(int)((t+w)/2); if(a[z]>=num) w=z; else t=z; if((w-t)==1){ if(a[w]==num){ printf("Has found %d,its position is %d",num,w+1); k=0; } else if(a[t]==num){ printf("Has found %d,its position is %d",num,t+1); k=0; } else {k=0;i=0;} } } } if(!i)printf("can not find %d",num); printf("\ncontinue or not(Y/N)?"); scanf(" %c",&c); if((c=='y')||(c=='Y')) i=1; else i=0; } } 比给的答案少用了两个变量,不过代码却多了两行,狂晕中,谭浩强《c程序设计(第三版)》习题7.9,我自己写的代码,运行与答案完全一样(是否继续那段开关代码除外) 昨天早晨从两点开写,改到八点下班都没改成功,极度抑郁,全删了。今晚先用笔把算法写在了纸上,照着算法写,写完改改,二十分钟成功,哈哈,彻底地体会到了“好记性不如烂笔头”这句话的含义啊!!!