C程序设计语言习题(1-13、14)

练习1-13 编写一个程序,打印输入中单词长度的水平直方图

#include<stdio.h>

#define IN 1 /*在单词内*/
#define OUT 0 /*在单词外*/
#define MAXHIST 15
#define MAXWORD 11

int main()
{
int c, i, nc, state;
int len;
int maxvalue;
int ovflow;
int wl[MAXWORD];

state = OUT;
nc = 0;
ovflow = 0;
for(i = 0; i < MAXWORD; ++i)
wl[i] = 0;
while ((c = getchar()) != EOF) {
if(c == ' ' || c == '\n' || c == '\t') {
state = OUT;
if(nc > 0)
if(nc < MAXWORD)
++wl[nc];
else
++ovflow;
nc = 0;
} else if (state == OUT) {
state = IN;
nc = 1;
} else
++nc;
}
maxvalue = 0;
for(i = 1; i < MAXWORD; ++i)
if(wl[i] > maxvalue)
maxvalue = wl[i];
for(i = 1; i < MAXWORD; ++i) {
printf("%5d - %5d : ", i, wl[i]);
if(wl[i] > 0) {
if((len = wl[i] * MAXHIST / maxvalue) <= 0)
len = 1;
} else
len = 0;
while (len > 0) {
putchar('*');
--len;
}
putchar('\n');
}
if(ovflow > 0)
printf("There are %d words >= %d\n", ovflow, MAXWORD);

return 0;
}


练习1-14 编写一个程序,打印输入中各个字符出现频率的直方图
#include<stdio.h>

#define IN 1 /*在单词内*/
#define OUT 0 /*在单词外*/
#define MAXHIST 15
#define MAXWORD 11
#define MAXCHAR 128

int main()
{
int c, i;
int len;
int maxvalue;
int cc[MAXCHAR];

for(i = 0; i < MAXCHAR; ++i) /*初始化字符个数统计数组*/
cc[i] = 0;
while((c = getchar()) != EOF)
if(c < MAXCHAR)
++cc[c];
maxvalue = 0;
for(i = 1; i < MAXCHAR; ++i)
if(cc[i] > maxvalue)
maxvalue = cc[i];

for(i = 1; i < MAXCHAR; ++i) {
if(isprint(i))
printf("%5d - %c - %5d : ", i, i, cc[i]);
else
printf("%5d - -%5d : ", i, cc[i]);
if(cc[i] > 0) {
if((len = cc[i] * MAXHIST / maxvalue) <= 0)
len = 1;
} else
len = 0;
while(len > 0) {
putchar('*');
--len;
}
putchar('\n');
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值