- 论坛徽章:
- 0
|
k&r 里的练习题 1-13, 我自己写的:- #include <stdio.h>
- #define MAXLEN 15
- int main()
- {
- int c, len, ovflow;
- int chars[MAXLEN];
- len = ovflow = 0;
- for (int i = 0; i < MAXLEN; ++i) {
- chars[i] = 0;
- }
- while ((c = getchar()) != EOF) {
- if (c == ' ' || c == '\n' || c == '\t') {
- ++chars[len];
- len = 0;
- }
- else {
- ++len;
- if (len > MAXLEN) {
- ++ovflow;
- len = 0;
- }
- }
- }
- for (int i = 1; i < MAXLEN; ++i) {
- printf("%02d | ", i);
- for (int j = 0; j < chars[i]; ++j) {
- printf("*");
- }
- printf("\n");
- }
- printf("OF | %d\n", ovflow);
- }
复制代码 完事我看了下习题解答, 他是这样的写的:- #define MAXHIST 15
- #define MAXWORD 11
- #define IN 1
- #define OUT 0
- int main()
- {
- int c, nc, state, len, ovflow, maxvalue;
- int wl[MAXWORD];
- // nc 单词长度
- // ovflow 大于最大字符长度(MAXWORD)的单词书
- // maxvalue wl下最长的一个
- nc = len = ovflow = maxvalue =0;
- state = OUT;
- for (int 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) {
- ++ovflow;
- }
- else {
- ++wl[nc];
- }
- }
- nc = 0;
- }
- else if (state == IN) {
- state = IN;
- nc = 1;
- }
- else {
- ++nc;
- }
- }
- // 找出最长的单词
- for (int i = 1; i < MAXWORD; ++i) {
- if (wl[i] > maxvalue) {
- maxvalue = wl[i];
- }
- }
- for (int 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');
- }
- }
复制代码 那种合适呢? |
|