我正在做所有K & R练习,并且我终于能够打印水平直方图。它看起来很糟糕,但我会让你判断它。我没有能够垂直打印输入文字长度的直方图。什么方法(使用stdio)可以打印垂直直方图
如何修改我的程序来做到这一点?
问题:编写一个程序,打印输入中的文字 的长度直方图。用水平方向 绘制柱状图很容易;垂直方向更具挑战性。
histogram.c
#include <stdio.h>
#define MAX 10
#define IN 1
#define OUT 0
int main()
{
int c, len, state;
int nlength[MAX];
c = len = 0;
state = 1;
for(int i = 0; i < 10; ++i)
nlength[i] = 0;
while ((c = getchar()) != EOF) {
++len;
if (c == ' ' || c == '\n' || c == '\t') {
--len;
state = OUT;
}
if(state == OUT) {
if(len != 0 && len <= MAX)
++nlength[len];
len = 0;
state = IN;
}
}
for (int i = 0; i <= MAX; ++i) {
printf("%d ", i);
for (int a = 0; a < nlength[i]; ++a)
printf("*");
printf("\n");
}
return 0;
}
OUTPUT:
./histogram < histogram.c
0
1 *************************************
2 *************************
3 **************
4 ************
5 *****
6 ******
7 ****
8 **
9 *
10 ***
使用'的printf( “%2D”,I);'在当前程序左对齐你的''秒。 –
@意义事项我不知道,谢谢。 – TheBlueCat