2017-10-28 103 views
-4

我正在尝试编写一个函数,它接受一个int数组作为参数,并为该数组中的数据写入一个带有'*'的直方图。从数组中的数据绘制直方图

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

histogram

我应该怎么写这个代码?

我的代码:

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); 

    } 
+0

你错过了这个问题... – DimChtz

+0

_“我有绘图直方图的问题”_不是一个有效的问题陈述。您需要告诉我们您正在尝试的是什么,您遇到什么问题,您期望的行为,您正在观察的行为等。请访问[help center](http://stackoverflow.com) /帮助),并阅读部分[我如何问一个好问题](http://stackoverflow.com/help/how-to-ask)。 –

+0

对不起。我的错。我编辑它。 – gallrdm

回答

0

这里是如何的代码应工作

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); 

} 

因为一切都在同一时间进行打印时,要确保*时,才会打印,如果阵列说它应该在这个高度打印。