什么样的方式(使用标准输入输出)我可以打印垂直直方图 [英] What ways (using stdio) can I print a vertical histogram
问题描述
我做的所有的K&放大器; R练习,我终于能够打印水平直方图。它看起来很不好过,但我会让你判断它。我一直没能打印的单词长度的直方图在其输入垂直。
如何修改我的程序做到这一点?
问:编写一个程序,如果打印的字长度的直方图
在它的输入。这是很容易绘制条形直方图
水平;垂直方向是更具挑战性。
块引用>histogram.c
的#include<&stdio.h中GT;
#定义MAX 10
的#define IN 1
#定义OUT 0诠释的main()
{
INT C,LEN,状态;
INT nlength [MAX];
C = LEN = 0;
状态= 1; 对(INT I = 0; I&小于10 ++ⅰ)
nlength [I] = 0; 而((C =的getchar())!= EOF){
++ LEN;
如果(C ==''||ç=='\\ n'||ç=='\\ t'){
--len;
状态= OUT;
}
如果(状态== OUT){
如果(LEN = 0&安培;!&放大器; LEN< = MAX)
++ nlength [LEN] LEN = 0;
状态= IN;
}
}
的for(int i = 0; I< = MAX; ++ I){
的printf(%D,我);
对于(int类型的= 0; A< nlength [I] ++一)
的printf(*); 的printf(\\ n);
}
返回0;
}OUTPUT:
./histogram< histogram.c
0
1 *************************************
2 *************************
3 **************
4 ************
5 *****
6 ******
7 ****
8 **
9 *
10 ***
解决方案首先,你需要知道哪些是最大值直方图的高度。然后,您打印的每一行,你决定把一个
*
或根据该值。
INT h_max = 0;
对于(int类型的= 0; A< MAX; A ++){
如果(h_max&下; = nlength [α])h_max = nlength [α];
}的for(int i = h_max; I> = 0;我 - ){
对于(int类型的= 0; A< MAX; ++一){
如果(nlength [α] I标记){
的printf(*);
}其他{
的printf();
}
}
的printf(\\ n);
}另一个解决方案是水平地打印到一个数组并打印在想要的方向上的阵列
I'm doing all the K&R exercises and I have finally been able to print a horizontal histogram. It look awful too, but I'll let you judge it. I have not been able to print a histogram of the lengths of words in its input vertically.
How can I modify my program to do this?
Question: Write a program to print a histogram of the lengths if words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.
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 ***
解决方案First you need to know the height of the histogram which is the maximum value. Then you print each row and you decide to put a
*
or aaccording to the value.
int h_max = 0; for (int a = 0; a < MAX; a++) { if (h_max <= nlength[a]) h_max = nlength[a]; } for (int i = h_max; i >= 0; i--) { for (int a = 0; a < MAX; ++a) { if (nlength[a] > i) { printf("*"); } else { printf(" "); } } printf("\n"); }
Another solution is to print horizontally into an array and print the array in the direction you want.
这篇关于什么样的方式(使用标准输入输出)我可以打印垂直直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!