C-打印直方图

标签 c histogram

这是 K&R 提出的问题:-

编写一个程序来打印输入中单词长度的直方图。绘制水平条形的直方图很容易;但垂直方向更具挑战性。

我不应该使用任何库函数,因为这只是一个教程介绍!

我编写了以下程序来执行此操作,但它有一些错误:-

1)如果单词之间有多个空白字符,程序将无法按预期运行。

2)我如何知道“k”的最大值我的意思是如何知道输入中有多少个单词?

这是代码:-

#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#define MAX_WORDS 100

int main(void)
{
    int c, i=0, k=1, ch[MAX_WORDS] = {0};

    printf("enter the words:-\n");

    do
    {
        while((c=getchar())!=EOF)
        {
            if(c=='\n' || c==' ' || c=='\t')
                break;
            else
                ch[i]++;
        }
        i++;
    }
    while(i<MAX_WORDS);

    do
    {
        printf("%3d|",k);
        for(int j=1;j<=ch[k];j++)
            printf("%c",'*');
        printf("\n");
        k++;
    }
    while(k<10);
}

最佳答案

即使两个单词之间有多个换行符,该程序也能正常工作,并且 numWords 将为您提供单词数。

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    int ch, cha[100] = {0}, k = 1;
    int numWords = 0;
    int numLetters = 0;
    bool prevWasANewline = true;     //Newlines at beginning are ignored

    printf("Enter the words:-\n");
    while ((ch = getchar()) != EOF && ch != '\n')
    {
        if (ch == ' ' || ch == '\t')
            prevWasANewline = true;  //Newlines at the end are ignored
        else
        {
             if (prevWasANewline)     //Extra nelines between two words ignored
             {
                  numWords++;
                  numLetters = 0; 
             }
             prevWasANewline = false;
             cha[numWords] = ++numLetters; 
        }

    }

    do
    {
        printf("%3d|",k);
        for(int j=0;j<cha[k];j++)
            printf("%c",'*');
        printf("\n");
        k++;
    } while(k <= numWords);

    return 0;
}      

关于C-打印直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18930908/

相关文章:

c - 这个程序如何在 C 中有这个输出

c - UVa 102 - Ecology Bin Packing 错误答案

c - header 中定义的 TypeDef 结构

sql - 从数据库中的列值生成直方图

给定分箱数据的python绘制简单直方图

python - 如何在 Matplotlib 中手动指定 bins?

c - 二维数组的定义和索引 - C

python - 如何在Python中将多个直方图堆叠在一个图中?

pandas - 如何并排绘制2个直方图?

c - 将硬安装的 NFS 卷视为软卷