在本教程中,我们将讨论一个程序,该程序通过数组内部给出的数据来制作直方图。
为此,我们将在数组内提供整数值。我们的任务是绘制直方图,使两个坐标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