1-14 编写一个程序,打印输入中各个字符出现频度的直方图

发布时间 2023-07-11 23:36:49作者: 语巫

Archlinux

GCC 13.1.1  20230429

2023-07-11 23:25:36 星期二

 


做了调整,只输出大小写字母共计56个字符的横向直方图,如有其他需要,自行添加。


点击查看代码
#include<stdio.h>


#define TRUE 1
#define FALSE 0


int main()
{
    int c_in;
    int c_num[52];
    int c_tmp[52];

    c_in = 0;
    for( int c=0; c<52; c++ ){
        c_num[c] = 0;
        c_tmp[c] = 0;
    }


    while( (c_in=getchar()) != EOF ){       //记录大小写字母频率
        if( c_in >= 'A' && c_in <= 'Z' ){
            c_num[c_in - 'A']++;
        }
        if( c_in >= 'a' && c_in <= 'z' ){
            c_num[c_in - 'a' + 26]++;
        }
    }

/*
    for( int n=0; n<52; n++ ){          //测试数据记录是否准确
        printf("%d", c_num[n]);
    }
    puts("");
*/
    for( int j=0; j<52; j++ ){
        if( (j < 26) && (c_num[j] != 0)){
            printf("%c: ", 65+j);
        }
        if( (j>26 && j<52) && (c_num[j] != 0) ){
            printf("%c: ", 97-26+j);
        }

        while( c_num[j] != 0 )
        {
            printf("#");
            c_num[j]--;
            if( c_num[j] == 0 ){
                puts("");
            }
        }
    }


    return 0;
}

 


运行截图:

image

image

输出正确。

 


小白刚学习C语言,代码质量不高,欢迎评论。