用星号绘制一个矩形
Draw A Rectangle With Asterisks
我正在尝试编写一个C++程序来显示一个用星号绘制的矩形。我让程序正常运行,除了只打印矩形高度的一侧。这是我目前为显示矩形方法编写的代码。
void Rectangle::displayRectangle()
{
int i=0, j=0;
for (int i = 0; i < width; i++)
{
cout << "*";
}
cout << endl;
for (int i = 0; i < height - 2; i++)
{
cout << "*";
for (int j = 0; j < width; j++)
{
cout << " ";
}
cout << endl;
}
for (int i = 0; i < width; i++)
{
cout << "*";
}
cout << endl;
}
在开始时指定宽度和高度,然后只需要 3 个循环。第一个将打印矩形的顶线。第二个将打印矩形的两侧(减去边的最顶部和最底部)。第三个将打印矩形的底线。
这样
// Width and height must both be at least 2
unsigned int width = 7; // Example value
unsigned int height = 5; // Example value
// Print top row
for(unsigned int i = 0; i < width; i++);
{
std::cout << "*";
}
std::cout << std::endl;
// Print sides
for(unsigned int i = 0; i < height - 2; i++)
{
std::cout << std::setw(width - 1) << std::left << "*";
std::cout << "*" << std::endl;
}
// Print bottom row
for(unsigned int i = 0; i < width; i++)
{
std::cout << "*";
}
std::endl;
您需要同时包含iostream
和iomanip
才能正常工作(setw
是iomanip
的一部分)。
顶部和底部行也可以使用该方法用给定字符填充空格来完成,但我现在不记得那个方法了。
这可以更容易、更清晰地完成。
这里的逻辑是从一行到另一行绘制,所以你只需要一个循环
(我选择在这个例子中使用自动说明符,因为我认为它看起来更整洁,并且在现代 c++ 中经常使用,如果你的编译器不支持 c++11,请使用 char、int 等):
int main()
{
using namespace std;
auto star = '*';
auto space = ' ';
auto width = 20;
auto height = 5;
auto space_cnt = width-2;
for (int i{0}; i != height+1; ++i) {
// if 'i' is the first line or the last line, print stars all the way.
if (i == 0 || i == height)
cout << string(width, star) << endl;
else // print [star, space, star]
cout << star << string(space_cnt, space) << star << endl;
}
}
好吧,你看不到第二条垂直线,因为你没有在线循环中绘制它。
void DrawRect(int w, int h, char c)
{
cout << string(w, c) << 'n';
for (int y = 1; y < h - 1; ++y)
cout << c << string(w - 2, ' ') << c << 'n';
cout << string(w, c) << 'n';
}
尝试提示用户输入行数和列数。然后,使用嵌套循环,根据用户输入显示一个星形矩形。
相关文章:
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 绘制一个对象,比较模具缓冲区的两个不同值
- 使用 glDrawElements 绘制一个 std::vector
- 我正在尝试创建一个 C++ 贪吃蛇游戏,但我似乎无法绘制第二个高度边框,我该如何解决这个问题?
- 如何在openGL C++中绘制一个空心圆
- 尝试绘制存储在数组中的矩形,但只出现一个矩形?
- Opencv,在图像中的对象周围绘制一个框
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- 图层不会绘制另一个图层
- 绘制椭圆延迟并绘制另一个椭圆延迟
- OPENCV C .在for循环中在不同的图像像素上绘制一个圆圈(应在每个循环运行时将图像打开)
- 直接X 11:在屏幕上绘制一个简单的彩色矩形
- 使用 C++ 库 GLEW 在 openGl 中绘制一个红色三角形
- 在另一个线程中绘制 OpenGL
- 如何在 MFC 中围绕当前光标的位置绘制一个矩形
- SFML在另一个对象上方绘制对象
- 创建一个包含要绘制的项的类(seg-fault)
- 为什么我的 OpenGL 对象相对于最后一个绘制的对象绘制
- 如何保持一个绘制矩形在相同的地方,因为相机周围移动
- 是否有可能保存当前的视口,然后在OpenGL和c++中在下一个绘制周期中重新绘制保存的视口?