【问题标题】:Drawing histogram from data in array从数组中的数据绘制直方图
【发布时间】:2017-10-28 23:01:37
【问题描述】:

我正在尝试编写一个函数,它以一个 int 数组作为参数,并为数组中的数据编写一个带有“*”的直方图。

例如,对于 int arr[]{2,1,0,7,1,9},我们应该得到:

我应该如何编写这段代码?

我的代码:

    using namespace std;

    int max = 0;
    char znak = '*';

    void histo(int arr[], size_t size) {
        for (int i = 0; i < size; i++) {
            if (arr[i] > max)
                max = arr[i];
        }

//drawing histogram

while (max > 0) {
            for (int i = 0; i < size; i++) {
                if (arr[i] >= max) {
                    cout << znak << " ";
                }
                else {
                    cout << " ";
                }
            }
            max--;
        }

    }


    int main()
    {
        int arr[]{2,1,0,7,1,9};
        size_t size = sizeof(arr) / sizeof(*arr);
        histo(arr, size);

    }

【问题讨论】:

  • 你错过了这个问题......
  • “我在绘制直方图时遇到问题” 不是有效的问题陈述。你需要告诉我们你正在尝试什么,你遇到了什么问题,你期望什么行为,你正在观察什么行为等等。请访问help center并阅读how do I ask a good question部分。
  • 对不起。我的错。我编辑了它。

标签: c++ arrays histogram


【解决方案1】:

这是代码的工作方式

char znak = '*';

void histo(int arr[], size_t size) {

    //finding the top point of this hystogram
    int max = arr[0];
    for (int i = 0; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    int level = max;
    int currSize =0;
    while (level != 0) {
        for (int i = 0; i < size; i++) {
            currSize = arr[i];
            if (currSize >= level) {
                cout << znak;
            }
            else
            {
                cout << " ";
            }
        }
        level--;

        cout << "\n";
    }
}
int main()
{
    int arr[]{2,1,0,7,1,9};
    size_t size = sizeof(arr) / sizeof(*arr);
    histo(arr, size);

}

因为必须同时打印所有内容,所以您要确保仅在数组表示它应该在该高度打印时才打印 *。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-14
    • 2013-11-04
    • 1970-01-01
    • 2020-09-25
    • 2012-02-07
    • 2023-03-08
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多