在C 中使用递归绘制图案

Drawing a pattern using recursion in c++

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

使用C 14,我尝试使用递归来绘制以下模式:我试图绘制的模式。

void drawPattern(int width, int startcol){
  if (width > 0){
    for (int i=0; i<width; i++){
        cout << "*";
    }
    for (int i=0; i<startcol; i++){
        cout << " ";
    }
    cout << "n";
    drawPattern(width/2, startcol);
    drawPattern(width/2, startcol+1);
    for (int i=0; i<startcol; i++){
        cout << " ";
    }
    for (int i=0; i<width; i++){
        cout << "*";
    }
  }
}

我一直很难将头缠绕在递归上。这个让我难过。

从图像中,我们看到下半场就像上半场一样,除了下半场在上半场之后开始了他的位置。第一和最后一行绘制n-thengent'*'如果n是当前长度。

#include <iostream>
using namespace std;
void Draw(int pos, int len, bool fw) {
    cout << string(pos, ' ') << string(len, '*') << endl;
    if (len > 1) {
        Draw(pos, len / 2, true);
        Draw(pos + len / 2, len / 2, false);
    }
    cout << string(pos, ' ') << string(len, '*') << endl;
}
int main() {
    Draw(0, 8, true);
    return 0;
}