[英]Drawing a pattern using recursion in c++
我正在使用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是當前長度,則第一行和最后一行繪制第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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.