如何在c++中打印垂直直方图
How to print a vertical histogram in C++
#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();`
}
>
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 如何在c++中仅使用for循环打印此代码的垂直直方图
- 垂直打印文字
- 在C中垂直打印字节数组
- 垂直打印树
- 如何在c++中打印垂直直方图
- 使用光标操作打印垂直直方图c++ [ncurses][解决了无ncurses]