zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

字符输入程序 一个 出现 编写 练习 打印
2023-09-14 09:06:57 时间

C语言程序设计(第二版) 练习1-14 个人设计

编写一个程序,打印输入中各个字符出现频度的直方图(水平)

代码块

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int c, nletter, nwhite, nother, i;                         /*定义字符,字母个数,空白个数,其他字符个数*/
    nletter=nwhite=nother=0;                                  /*变量初始为0*/
    while ((c=getchar())!=EOF){                               /*当输入字符不是文件结束符时*/
        if ((c>='A'&&c<='Z')||(c>='a'&&c<='z'))               /*如果输入字符为字母*/
            ++nletter;                                        /*字母统计个数增加1个*/
        else if (c==' '||c=='\t'||c=='\n')                    /*如果输入字符为空格或制表符或换行符*/
            ++nwhite;                                         /*空白统计个数增加1个*/
        else
            ++nother;                                         /*其他字符增加1个*/
    }
    printf(" nletter %3d  ", nletter);                        /*此五行为输出字母直方图*/
    for (i=1; i<=nletter; ++i)
        printf("*");
    printf("\n");
    printf(" nwhite %3d  ", nwhite);                          /*此五行为输出空白直方图*/
    for (i=1; i<=nwhite; ++i)
        printf("*");
    printf("\n");
    printf(" nother %3d  ", nother);                          /*此五行为输出其他字符直方图*/
    for (i=1; i<=nother; ++i)
        printf("*");
    printf("\n");
    system("pause");
    return 0;
}

如果程序设计有错误或更简洁的方法,欢迎并感谢您指正出示,谢谢!