编写一个程序来打印输入中单词长度的直方图。用水平条形图很容易画出直方图;而垂直方向则更具挑战性。
我认为一切都运行得很好,除了当我尝试确定最后一个单词计数(变量tmp)是否<=10或>10时,将其分配给count[tmp-1]或count[11](如果大于)。就算不打印实际的直方图,现在我只想要一个有效的数组表示。下面是程序运行时的输出。
asdasd
_________________________________
1 2 3 4 5 6 7 8 9 10 11
(x-axis) Length of words
---------------------------------
[0 SPACE] [0 NEWLINE] [0 TAB]
[1 WORD] [0.000 KILOBYTE] [6 CHAR]
6---
ARRAy= 1 1 1 1 1 2 0 0 0 0
这是我的代码
#include <stdio.h>
#define MAX 10
int main (void) {
//
int nc,nw,nt,ns,nl; //nc = bytes, nw = words, nt = tabs, ns = spaces, nl = newlines
nc = nw = nt = ns = nl = 0;
//
int c; //getchar()
int done = 0; //don't even know I'm a noob just ignore...
int tmp = 0; //last word count (this works well)
int array[MAX + 1]; //For outputting screen formatters like ---
int count[11]; //THIS is whats broken random values
int state = 0;
int waslast = 0;
float kbcount = 0;
for (c = 0; c <= MAX; c++)
count[c] = 0;
while (done == 0) {
c = getchar();
++nc;
if (c == ' ' || c == '\n' || c == '\t') {
waslast = 1;
if (c == '\t') {
++nt;
state = tmp;
tmp = 0;
}
else if (c == '\n') {
++nl;
state = tmp;
tmp = 0;
}
else if (c == ' ') {
++ns;
state = tmp;
tmp = 0;
}
}
if (c == EOF) {
done = 1;
}
else if (c != ' ' && c != '\n' && c != '\t') {
tmp++;
state = tmp;
if (waslast == 1) {
nw++;
waslast=0;
}
if (nc == 1)
nw++;
}
if (tmp <= 10)
count[tmp-1]++; //Completely random assignments
else
count[11]++; //This is broken
}
// END WHILE
//
//
printf("\n");
for (c = 1; c <= MAX + 1; c++) {
printf("___");
}
printf("\n");
for (c = 1; c <= MAX + 1; c++) {
array[c] = c;
printf("%2d ", array[c]);
}
printf("\n (x-axis) Length of words \n");
for (c = 1; c <= MAX + 1; c++){
printf("---");
}
kbcount = (nc-1)/1024;
printf("\n[%d SPACE] [%d NEWLINE] [%d TAB] \n[%d WORD] [%.3f KILOBYTE] [%d CHAR]\n\n\n\n%d---\n\n\n",
ns,nl,nt,nw,kbcount,(nc -(nl+nt+ns))-1,state);
printf("ARRAy=");
for (c = 0; c<MAX ;++c)
printf(" %d ",count[c]);
return 0;
}
~ ~
count[10]
创建了count[0]
、count[1]
、count[2]
、……和count[9]
。count[10]
是未定义的,但访问它很可能会导致一些不好的事情发生。 - wallyk