0818b9ca8b590ca3270a3433284dd417.png

统计文本单词长度出现频率并打印直方图。

#include

#define MAXHIST 15

#define MAXWORD 11 //统计最长单词的长度

#define IN 1 //状态标示

#define OUT 0

int main(){

int c,i,nc,state;

int len;

int maxvalue;

int ovflow;

int wl[MAXWORD];

state=OUT;

nc=0;

ovflow=0;

for(i=0;i

wl[i]=0;

while((c=getchar())!=EOF){

if(c==' '||c=='\n'||c=='\n'){

state=OUT;

if(nc>0){

if(nc

wl[nc]++;

else

ovflow++;

nc=0;

}

}else if(state==OUT){

state=IN;

nc=1;

}

else

nc++;

} //文本输入,统计各个长度单词出现频率

maxvalue=0;

for(i=1;i

if(wl[i]>maxvalue)

maxvalue=wl[i];

}

for(i=1;i

printf("%5d - %5d :",i ,wl[i]);

printf("%d ",len);

if(wl[i]>0){

if((len=wl[i]*MAXHIST/maxvalue)<=0) //画出直方图

len=1;

}else

len=0;

while(len>0){

putchar('*');

len--;

}

putchar('\n');

}

if(ovflow>0)

printf("There are %d words>= %d\n",ovflow,MAXWORD);

}

下面是竖状直方图,文本输入一样,关键利用二层循环嵌套输出*

#include

#define MAXHIT 15

#define MAXWORD 11

#define IN 1

#define OUT 0

int main(){

int c,i,j,nc,state;

int maxvalue;

int ovflow;

int wl[MAXWORD];

state=OUT;

nc=0;

ovflow=0;

for(i=0;i

wl[i]=0;

while((c=getchar())!=EOF){

if(c==' '||c=='\n'||c=='\t'){

state=OUT;

if(nc>0){

if(nc

wl[nc]++;

else

ovflow++;

}

nc=0;

}

else if(state==OUT){

state=IN;

nc=1;

}

else

nc++;

}

maxvalue=0;

for(i=1;i

if(wl[i]>maxvalue)

maxvalue=wl[i];

}

for(i=MAXHIT;i>0;--i){

for(j=1;j

if(wl[j]*MAXHIT/maxvalue>=i)

printf(" *");

else

printf(" ");

}

putchar('\n');

}

for(i=1;i

printf("%4d",i);

putchar('\n');

for(i=1;i

printf("%4d",wl[i]);

putchar('\n');

if(ovflow>0)

printf("There are %d words >=%d\n",ovflow

,MAXWORD);

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐