C语言K&R习题系列——统计一段文字中各个字母出现的频率

原题:

/*Write a program to print a histogram of the frequencies of 

 *difficent characters in it inputs

 */


这个和上一个类似


输入部分

#include < stdio.h >
  
 #define NUM_CHARS 256
  
 main ( void )
 {
    int c;
    int done = 0;
    int thisIdx = 0;
    long frequrr[NUM_CHARS + 1];
    long thisVal = 0;
    long maxVal = 0;
    //initialize
    for ( thisIdx = 0; thisIdx <= NUM_CHARS; thisIdx++ )
    {
        frequrr[thisIdx] = 0;
    }
     
    while ( done == 0 )
    {
        c = getchar();
         
        if ( c == EOF )
        {
            done = 1;
        }
         
        if ( c < NUM_CHARS )
        {
            thisVal = ++frequrr[c];
            if ( thisVal > maxVal )
            {
                maxVal = thisVal;
            }
        }
        else 
        {
            thisVal = ++frequrr[NUM_CHARS];
            if ( thisVal > maxVal )
            {
                maxVal = thisVal;
            }
        }
    }


输出部分


for ( thisVal = maxVal; thisVal >0; thisVal-- )
    {
        printf ( "%2d |", thisVal );
        for ( thisIdx = 0; thisIdx <= NUM_CHARS; thisIdx++ )
        {
            if ( frequrr[thisIdx] >= thisVal )
            {
                printf ( "*" );
            }
            else if ( frequrr[thisIdx] > 0 )
            {
                printf ( " " );
            }
        }
        printf ( "\n" );
    }
    printf ( "   |_" );
    for ( thisIdx = 0; thisIdx < NUM_CHARS + 1; thisIdx++ )
    {
        if ( frequrr[thisIdx] > 0 )
        printf ( "_");
    }
    printf ( "\n    " );
    for ( thisIdx = 0; thisIdx < NUM_CHARS + 1; thisIdx++ )
    {
        if ( frequrr[thisIdx] > 0 )
        printf ( "%d", ( thisIdx + 1 ) / 100 );
    }
    printf ( "\n    " );
    for ( thisIdx = 0; thisIdx < NUM_CHARS + 1; thisIdx++ )
    {
        if ( frequrr[thisIdx] > 0 )
        printf ( "%d", ( thisIdx + 1 ) / 10 % 10 );
    }
    printf ( "\n    " );
    for ( thisIdx = 0; thisIdx < NUM_CHARS + 1; thisIdx++ )
    {
        if ( frequrr[thisIdx] > 0 )
        printf ( "%d", ( thisIdx + 1 ) % 10 );
    }
    printf ( "\n" );
    return 0;
 }


运行结果



C语言K&R习题系列——统计一段文字中各个字母出现的频率_第1张图片









你可能感兴趣的:(C/C++)