书后练习--直方图
程序不是很复杂,就是调节显示样式花点时间!!
#include <stdio.h> #define LENGTH 10 /* 打印输出单词的长度的直方图 */ void main() { /* x_length 单词的长度 */ int x_length, c, i, j; int arr[LENGTH] = {0}; x_length = i = j = 0; while ( (c = getchar() ) != EOF ) { if ( c == ' ' || c == '\n' || c == '\t') { if ( x_length >= LENGTH-1 ) { arr[LENGTH-1]++; } else { arr[x_length]++; } x_length = 0; } else { x_length++; } } printf("单词长度\n"); for ( i = LENGTH-1; i > 0; i--) { if ( i == LENGTH-1 ) { printf(" %d+|", i); } else { printf(" %2d|", i); } if ( arr[i] != 0 ) { for ( j = 1; j < arr[i]; j++ ) { printf(" "); } printf("*"); } printf("\n"); } printf(" "); for ( i = 1; i <= LENGTH-1; i++ ) { printf("- "); } printf("\n "); for ( i = 1; i <= LENGTH-1; i++ ) { if ( i == LENGTH-1 ) { printf(" %d+(单词出现次数)\n", i); } else { printf(" %2d", i); } } }
结果: