如何在c++中打印垂直直方图

How to print a vertical histogram in C++

本文关键字:打印 垂直 直方图 c++      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main()
{
    int a, b, c, i;
    cin >> a >> b >>  c;
    for ( i = 0;  i < a; i++)
        cout << "*" << endl;
    for ( i = 0; i < b; i++)
        cout << "*" << endl;
    for ( i = 0; i < c; i++)
        cout << "*" << endl;
}

我知道输出和

一样
for ( i = 0; i < a + b + c; i++ ){
cout << "*" << endl;
}

那么对于2 3 1,我得到:

*

*

*

*

*

*

我要的是:

     *
*    * 
*    *    *   //Horizontal distance between 2 shapes don't matter.

考虑到打印必须从上到下进行,我不知道如何将光标放在正确的位置。

EDIT:我不清楚打印的顺序。我希望下面的示例对您有所帮助,而且,如果可能的话,每一列的打印必须通过使用单独的函数来完成。

第一个循环:

*
*

第二个循环:

    *
*   *
*   *
去年循环:

    *
*   *
*   *   *

印刷必须完全按照这个顺序进行。先打印第一列,然后打印第二列,如下所示:

您需要重新考虑一下您的打印。首先,您需要找出最高的一列,因为这是您将拥有的行数。

我会这样做:

int high = std::max(std::max(a, b), c);
for (int i = high; i > 0; i--)
{
    if (i <= a)
        std::cout << " * ";
    else
        std::cout << "   ";
    if (i <= b)
        std::cout << " * ";
    else
        std::cout << "   ";
    if (i <= c)
        std::cout << " * ";
    else
        std::cout << "   ";
    std::cout << std::endl;
}

如果你想要任意数量的列,你可能想把它们放在std::vector中,并有一个内部循环。


对于任意数量的列,可以使用如下命令:

// Get the input
std::cout << "Please enter numbers, all on one line, and end with ENTER: ";
std::string input;
std::getline(std::cin, input);
// Parse the input into integers
std::istringstream istr(input);
std::vector<int> values(std::istream_iterator<int>(istr),
                        std::istream_iterator<int>());
// Get the max value
int max_value = *std::max_element(values.begin(), values.end());
// Print the columns
for (int current = max_value; current > 0; current--)
{
    for (const int& value : values)
    {
        if (current <= value)
            std::cout << " * ";
        else
            std::cout << "   ";
    }
    std::cout << std::endl;
}

代码:

#include <iostream>
using namespace std;
int f[3];
int main()
{
    int a, b, c, i;
    cin >> f[0] >> f[1] >>  f[2];
    int m = max(max(f[0],f[1]),f[2]);
    for(int i=m;i>=1;i--)
    {
        for(int j=0;j<3;j++)
            if (f[j]<i) cout <<' ';
            else cout <<'*';
        cout<<endl;
    }
}

测试:

Input: 2 3 1
Output:
 *
**
***

好代码,看看这个

#include<conio.h>
void main()
{
int a[5];
int i,j,max;
clrscr();
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
max=a[0];
if(max<a[i])
max=a[i];
}
printf("n");
for(i=0;i<max;i++)
{
putchar(max);
}
printf("n");
printf("n");
for(i=0;i<5;i++)
{
printf("%d t--->t",a[i],putchar(max));
for(j=1;j<=a[i];j++)
{
printf("*");
}
printf(" ");
printf("n");
}
printf("n");
for(j=max;j>0;--j)
{
putchar(max);
}
getch();`
}

>