用星号绘制一个矩形

Draw A Rectangle With Asterisks

本文关键字:一个 绘制      更新时间:2023-10-16

我正在尝试编写一个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;

您需要同时包含iostreamiomanip才能正常工作(setwiomanip的一部分)。

顶部和底部行也可以使用该方法用给定字符填充空格来完成,但我现在不记得那个方法了。

这可以更容易、更清晰地完成。
这里的逻辑是从一行到另一行绘制,所以你只需要一个循环
(我选择在这个例子中使用自动说明符,因为我认为它看起来更整洁,并且在现代 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';
}

尝试提示用户输入行数和列数。然后,使用嵌套循环,根据用户输入显示一个星形矩形。