第一步:
建立数组,并打印出不同长度的单词数目:
#include<stdio.h>
main()
{
int c, i;
int length = 0;
int pitLock = 1;
int charLen[10];
for (int i = 0; i < 10; i++)
charLen[i] = 0;
while ((c = getchar()) != EOF)
{
if ((c >= 'a') && (c <= 'z') && (pitLock == 1))
{
length++;
}
else if (pitLock == 1)
{
++charLen[length - 1];
length = 0;
}
else pitLock = 0;
}
for ( i = 0; i < 10; i++)
{
printf("length = %d: %d\n", i + 1, charLen[i]);
}
}
第二步:
调用函数实现星号直方图打印
#include<stdio.h>
void print_star(int);
main()
{
int c, i;
int length = 0;
int pitLock = 1;
int charLen[10];
for (int i = 0; i < 10; i++)
charLen[i] = 0;
while ((c = getchar()) != EOF)
{
if ((c >= 'a') && (c <= 'z') && (pitLock == 1))
{
length++;
}
else if (pitLock == 1)
{
++charLen[length - 1];
length = 0;
}
else pitLock = 0;
}
for ( i = 0; i < 10; i++)
{
printf("length = %2d: %4d |", i + 1, charLen[i]);
print_star(charLen[i]);
}
return 0;
}
void print_star(int num)
{
while (num) {
printf("*");
--num;
}
printf("\n");
}