我正在编写一个程序,该程序将读取输入,然后从K&R-Ex中返回字符计数的直方图。 1.13
关于如何改进代码的任何建议?我是否先测试状况或外出状态是否重要?我在示例中注意到人们进行了测试,首先检查c是空白还是制表符。
我认为我需要重新查看直方图。它并不能真正扩展结果。它只是根据长度绘制连字符。
修改后,我想使它更具可读性。
// Print a histogram of the length of words in it's input.
#include <stdio.h>
#define IN 1
#define OUT 2
#define MAX 99
int main(){
int c; // the character
int countOfLetters = 0;
int insideWord = OUT;
int frequencyOfLengths[MAX];
int longestWordCount = 0;
int i, j; // Counters
for (i = 0; i < MAX; i++){
frequencyOfLengths[i] = 0;
}
while ((c = getchar()) != EOF){
if (c == ' ' || c == '\n' || c == '\t'){
if (insideWord == IN){
if (countOfLetters > MAX){
return 1;
}
++frequencyOfLengths[countOfLetters];
if (countOfLetters >= longestWordCount) longestWordCount = countOfLetters;
}
countOfLetters = 0;
}
else {
countOfLetters++;
insideWord = IN;
}
}
for (i = 1; i <= longestWordCount; i++){
printf("%3i : %3i ", i, frequencyOfLengths[i]);
for (j = 0; j < frequencyOfLengths[i]; j++){
printf("*");
}
printf("\n");
}
return 0;
}
最佳答案
绝对缩放结果,检查我的Character Histogram,它执行水平缩放直方图。
同样,您可能会受益于y轴标签。很难确定哪种条长对应哪种字长。我不知道哪个小节适合哪个单词长度。
我在显示直方图之前就添加了此代码,它基本上将每个值减半,这确实使条码标签变得不正确。你可以弄清楚!
// Iterates and tells us the most frequent word length
int mostFrequent = 0;
for (i = 1; i < MAXWORD; i++)
if (charCount[i] > mostFrequent)
mostFrequent = charCount[i];
// If the bar will be too big, cut every value in half
while (mostFrequent > 60) {
for (i = 1; i < MAXWORD; i++)
if (charCount[i] > 0) {
charCount[i] /= 2;
charCount[i] |= 1;
}
// Check again to find the most frequent word length category
mostFrequent = 0;
for (i = 1; i < MAXWORD; i++)
if (charCount[i] > mostFrequent)
mostFrequent = charCount[i];
}
老实说,这些条很难读,也许只使用一行字符,例如█!
到目前为止,还不错的书,实际上我们正在一起阅读,并且在同一页上!
干杯
关于c - 需要一些有关如何更整洁地打印直方图的建议,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29321583/