如何在c++中仅使用for循环打印此代码的垂直直方图


//Program to Print Horizontal Histogram of Shape{*} 
#include<"iostream">
using namespace std;
int main() {
int a[100],n,i,j;
cout<<"Enter Size of Array"<<endl;
cin>>n;
cout<<"Enter Array Elemnts"<<endl;
for(i=0;i<n;i++) {
cin>>a[i];
}
for(i=0;i<n;i++) {
for(j=0;j<a[i];j++) {
cout<<"* ";
}
cout<<endl;
}
}

这段代码是在水平方向打印直方图,但我想从下到上在垂直方向打印它。

解决方案取决于柱是向下还是向上。除此之外,解决方案类似:

外部循环遍历行。内部循环遍历列以及相应的数组元素。如果值小于当前行,则打印实心字符,否则为空格。

对于必需的行数,数组中的最大值必须是已知的。对于向上指向的列,这必须在处理之前确定,因为它是外循环中迭代的起始值。

我的样本代码:

#include <iostream>
#include <vector>
#include <cmath>
int main()
{
int n = 10; // size of array
std::vector<int> a; // array elements
int maxA = 15;
for (int i = 0; i < n; ++i) a.push_back(rand() % maxA);
// print values
for (int value : a) std::cout << ' ' << value;
std::cout << 'n';
// determine max height of columns
maxA = 0;
for (int value : a) if (maxA < value) maxA = value;
// output maxA lines
for (; maxA > 0; --maxA) {
for (int value : a) std::cout << (value >= maxA ? " #" : "  ");
std::cout << 'n';
}
// done
return 0;
}

输出:

13 1 12 10 8 10 1 12 9 1
#                  
#   #         #    
#   #         #    
#   # #   #   #    
#   # #   #   # #  
#   # # # #   # #  
#   # # # #   # #  
#   # # # #   # #  
#   # # # #   # #  
#   # # # #   # #  
#   # # # #   # #  
#   # # # #   # #  
# # # # # # # # # #

coliru上的实时演示

include<quot;iostream">

使用命名空间std;

int main((

int a[100],i,j,n,max,copy;
cout<<"Enter the size of Array:"<<endl;
cin>>n;

for(i=0;i<n;i++)
{
cout<<"Enter the element:"<<i+1<<endl;
cin>>a[i];
}
//finding max no.
max=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
copy=max;
//logic for vertical histogram
cout<<"**********HISTOGRAM**********"<<endl;
for(i=0;i<copy;i++,max--)
{
for(j=0;j<n;j++)
{
if(a[j]>=max)
cout<<" * ";
else
cout<<"   ";
}
cout<<"n";
}

}

最新更新