用 C++ 制作数组直方图的程序


在本教程中,我们将讨论利用数组中提供的数据编写一个程序绘制直方图。

为此,我们将在数组中提供整数值。我们的任务是绘制一个直方图,使坐标 x 和 y 的值都等于数组中提供的值。

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
void make_histogram(int arr[], int n){
   int maxEle = *max_element(arr, arr + n);
   for (int i = maxEle; i >= 0; i--) {
      cout.width(2);
      cout << right << i << " | ";
      for (int j = 0; j < n; j++) {
         if (arr[j] >= i)
            cout << " x ";
         else
            cout << " ";
      }
      cout << "\n";
   }
   for (int i = 0; i < n + 3; i++)
   cout << "---";
   cout << "\n";
   cout << " ";
   for (int i = 0; i < n; i++) {
      cout.width(2);
      cout << right << arr[i] << " ";
   }
}
int main() {
   int arr[10] = { 10, 9, 12, 4, 5, 2,
   8, 5, 3, 1 };
   int n = sizeof(arr) / sizeof(arr[0]);
   make_histogram(arr, n);
   return 0;
}

输出

12 | x
11 | x
10 | x x
9 | x x x
8 | x x x x
7 | x x x x
6 | x x x x
5 | x x x x x x
4 | x x x x x x x
3 | x x x x x x x x
2 | x x x x x x x x x
1 | x x x x x x x x x x
0 | x x x x x x x x x x
---------------------------------------
10 9 12 4 5 2 8 5 3 1

更新时间: 2019-12-19

3 千次观看

事业的开端

完成课程,获得认证

开始使用
广告