明朝火枪威力:用c语言编写一个程序,打印输入单词的长度的直方图?

来源:百度文库 编辑:神马品牌网 时间:2024/04/28 02:27:13

/*
练习1.13;
编写一个程序,打印输入中长度的直方图。
*/
# include <stdio.h>
# define MAXHIST 15 //最大长度的直方图
# define MAXWORD 11 //一个单词的最大长度
# define IN 1 //文字内
# define OUT 0 //外一个单词

/*打印水平直方图*/
int main(void)
{
int c,i,nc,state;
int len; //每条的长度
int maxvalue; //最大者为
int ovflow; //数量的溢出的话
int wl[MAXWORD]; //单词长度计数器

state = OUT;
nc = 0; //在一个单词字符的数量
ovflow = 0; //字数> = MAXWORD
for(i = 0;i < MAXWORD; ++i)
wl[i] = 0;
while ((c = getchar()) != EOF)
{
if (c == ' ' || c == '\n' || c == '\t')
{
state = OUT;
if(nc > 0)

if(nc < MAXWORD) //如果nc小于11则wl[nc]元素加一
++wl[nc];
else //否则ovflow加一
++ovflow;

nc = 0;
}
else if (state == OUT)
{
state = IN;
nc = 1; //开始一个新单词
}
else
++nc; //文字内
}
maxvalue = 0;
for (i = 1; i < MAXWORD; ++i)
if(wl[i] > maxvalue)
maxvalue = wl[i];
for (i = 1; i < MAXWORD; ++i)
{
printf("%5d - %5d : ",i,wl[i]);
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);
return 0;
}

#include<stdio.h>
main()
{
FILE *f;
int i,j,flag,count;
char ch;
f=fopen("文件名","r");
ch=fgetc(f);
for(i=0;ch!=EOF;i++)
{if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z')
flag=1;
else
{ if(flag>0)
count++;
flag=0;
}

ch=fgetc(f);
}
printf("the length is %d",count);
}