编写一个程序,打印输入中单词长度的水平和垂直方向直方图
题目来源:C程序设计语言习题1-13
//横向打印输入中单词长度的直方图
#include<stdio.h>
#define MAXWORDNUM 100 //最大单词个数
main()
{
int c_last,c_now;
int i = 0,j = 0;
int len = 0,maxlen = 0; //每个单词的长度 ,最大单词长度
int num = 0;
int word[MAXWORDNUM]; //保存单词长度的数组
for (i = 0;i<MAXWORDNUM;i++)
word[i] = 0;
i = 0;
c_now = getchar();
c_last = c_now;
if (c_last != '\40' )
++len;
while ((c_now = getchar()) != EOF)
{
if ((c_now != '\40') && (c_now != '\n'))
++len;
if (((c_now == '\40') && (c_last != '\40')) || ((c_now == '\n') && (c_last != '\40')))
{
word[num]= len;
++num;
len = 0;
}
c_last = c_now;
}
for (i = 0;i<num;i++)
{
printf("%d:",i+1);
for (j = 0;j<word[i];j++)
printf("*");
printf("\n");
}
}
//纵向向打印输入中单词长度的直方图
#include<stdio.h>
#define MAXWORDNUM 100
main()
{
int c_last,c_now;
int i = 0,j = 0;
int len = 0,maxlen = 0;
int num = 0;
int word[MAXWORDNUM];
for (i = 0;i<MAXWORDNUM;i++)
word[i] = 0;
i = 0;
c_now = getchar();
c_last = c_now;
if (c_last != '\40' )
++len;
while ((c_now = getchar()) != EOF)
{
if ((c_now != '\40') && (c_now != '\n'))
++len;
if (((c_now == '\40') && (c_last != '\40')) || ((c_now == '\n') && (c_last != '\40')))
{
word[num]= len;
if (word[num] > maxlen)
maxlen = word[num];
++num;
len = 0;
}
c_last = c_now;
}
for (j = maxlen;j>0;j--)
{
for (i = 0;i<num;i++)
{
if (word[i] >= j)
printf("* ");
else
printf(" ");
}
printf("\n");
}
for (i = 0;i<num;i++)
printf("%d ",i+1);
}
本文提供两个C语言程序示例,分别用于打印输入中单词长度的水平和垂直直方图。通过分析输入文本,程序统计每个单词的长度,并以此为基础绘制直方图。

2376

被折叠的 条评论
为什么被折叠?



