Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình vẽ histogram từ mảng C++


Trong hướng dẫn này, thảo luận chương trình vẽ histogram từ dữ liệu mảng.

Cho giá trị nguyên trong mảng. Nhiệm vụ vẽ histogram tọa độ x và y bằng giá trị trong mảng.

Ví dụ mã nguồn

#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; }

Kết quả

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