十几年前写的文章,当时我记得是调试通过了的,不过这里贴的代码可能也有错误.有需要学习C语言作参考的同学自行甄别,因为写的时候中文乱码就没怎么加注释了.
任何学习最好的方式是独立思考并且原创,高手写得再好那也是别人的原创,不是自己的学习成果.所以最好的学习方法是独立思考并原创,再去参考别人写得比自已更好的算法,借鉴吸收改进.
我这文章算是自己当时重温C语言的记录了,也懒得改了.这篇文章主要供C语言初学者参考借鉴.
别人写得再好也是别人的知识. 独立思考很重要, 原创很重要, 借鉴吸收再改进当然也重要.
/*C程序设计语言(第二版)-练习1-13 打印输入中单词的直方图*/
/*实现功能:打印输入中所有单词字符数量统计直方图*/
#include <stdio.h>
#define MAXLEN 10 //单词最大字符数
#define IN 1 //处在单词中
#define OUT 0 //出单词状态
main()
{
int Word[MAXLEN], WordState = OUT;
int WordLen, MaxNum, InitValue, WordNum, NormalLine, LastTwoLine, LastTwoColumn, c;
WordLen = MaxNum = InitValue = WordNum = NormalLine = LastTwoLine= LastTwoColumn = 0;
for (; InitValue <= MAXLEN; InitValue++)
Word[InitValue] = 0;
while ((c = getchar()) != EOF){ //从用户获取输入
if (c == ' ' || c == '\t' || c == '\n'){
if (WordState == IN){ //输入特殊字符, 空格, table键, 换行键
++Word[WordLen - 1]; //长度记录在数组中
WordLen = 0;
WordState = OUT;
}
}
else if (WordState == OUT){
++WordLen;
WordState = IN;
}
else if (WordState == IN){
++WordLen;
}
}
printf("\n");
MaxNum = Word[WordNum];
for (; WordNum <= MAXLEN - 1; ++WordNum)
if (Word[WordNum] > MaxNum)
MaxNum = Word[WordNum];
printf("\n\n Y This value is the counts of words\n");
printf(" |\n");
for (NormalLine = MaxNum + 2; NormalLine >= 0; --NormalLine){
if (NormalLine != 0){
printf("=|", NormalLine);
for (WordNum = 0; WordNum < MAXLEN; ++WordNum){
if (Word[WordNum] >= NormalLine)
printf(" *");
else
printf(" ");
}
printf("\n");
}
else //print the last two line and length symbol of word
for (LastTwoLine = 0; LastTwoLine <= 1; ++LastTwoLine){
if (LastTwoLine != 0){
printf(" 0 ");
for (LastTwoColumn = 0; LastTwoColumn < MAXLEN; ++LastTwoColumn)
printf("=", LastTwoColumn + 1);
printf("\n");
}
else{
printf(" +");
for (LastTwoColumn = 0; LastTwoColumn < MAXLEN; ++LastTwoColumn)
printf("---");
printf("--->X This value is length of word\n");
}
}
}
printf("Press any key to exit");
getchar();
}
/*运行效果*/