练习 1-13 编写一个程序,打印输入中单词长度的直方图。水平方向的直方图比较容易绘制,垂直方向的直方图则要困难些。
#include<stdio.h>
#define MAX 9//max of word length
#define WORD 1//one stateof the input
#define BLANK 0//the other state of the input
int main() {
printf("Please enter some words, then you'll get a histogram of word length\n");
int c;
int wordlength= 0;
int state = BLANK;
int word[MAX]={0};
int overflow = 0;
while ((c = getchar()) != EOF) {
if ((c != ' ') && (c != '\n')) {
state = WORD;
++wordlength;
}
else {
if(state==WORD){
if(wordlength<=MAX){
state = BLANK;
++word[wordlength-1];
wordlength = 0;
}else{
state = BLANK;
++overflow;
wordlength = 0;
}
}
}
}
printf("----------------------------------------\n");
for(int i=0;i<MAX;++i){
printf("%3d",i+1);
if(word[i]>0){
for(int j=0;j<word[i];++j){
printf("*");
}
}
printf("\n");
}
printf(" >%d",MAX);
for(int j=0;j<overflow;++j){
printf("*");
}
printf("\n----------------------------------------\n");
int m=0;
for(int i=0;i<MAX;++i){
if(m<word[i]){
m=word[i];
}
}
for(int i=m;i>0;--i){
printf("%2d",i);
for(int j=0;j<MAX;++j){
if(word[j]>=i){
printf(" *");
}else{
printf(" ");
}
}
if(overflow>=i){
printf(" *");
}else{
printf(" ");
}
printf("\n");
}
printf(" ");
for(int i=1;i<=MAX;++i){
printf("%3d",i);
}
printf(" >%d",MAX);
printf("\n");
return 0;
}
简单输了一段英文后结果如下:(第一个是水平分布直方图,第二个是垂直分布直方图)
练习 1-22 编写一个程序,把较长的输入行“折”成短一些的两行或多行,折行的位置在输入行的第n 列之前的最后一个非空格之后。要保证程序能够智能地处理输入行很长以及在指定的列前没有空格或制表符时的情况。
#include <stdio.h>
#include <stdlib.h>
int get(char s[],int m);
int main() {
char line[1000];
int size;
size=get(line,1000);
int kong1=0;
int kong2;
int ge=0;;
for(int i=0;i<size;++i){
if((line[i]==' ')||(line[i]=='\n')){
kong2=i;
if((ge+kong2-kong1)<21){
for(int ii=kong1;ii<=kong2;++ii){
putchar(line[ii]);
}
ge=ge+kong2-kong1+1;
kong1=kong2+1;
}else{
printf("\n");
ge=0;
for(int ii=kong1;ii<=kong2;++ii){
putchar(line[ii]);
}
ge=ge+kong2-kong1+1;
kong1=kong2+1;
}
}
}
return 0;
}
int get(char s[],int m){
int c;
int i=0;
while(((c=getchar())!=EOF)){
s[i]=c;
++i;
}
s[i]='\n';
return i;
}
输出结果如下:(每行不超过20个字符)