use*_*092 5 c arrays histogram
我正在阅读C编程语言第二版.我参加了这个练习[第1.6节,第 1节,第 13 页.24第2版 ].
编写一个程序来打印输入中单词长度的直方图.可以很容易地绘制水平条形图的直方图; 垂直方向更具挑战性.
我认为一切都很好用,除非我试图确定最后一个字数(VARIABLE 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
Run Code Online (Sandbox Code Playgroud)
这是我的代码
#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;
}
Run Code Online (Sandbox Code Playgroud)
~~
| 归档时间: |
|
| 查看次数: |
247 次 |
| 最近记录: |