更新:
通过一些优化并以 n 作为行数而不是基本宽度,我们得到了一些非常简单的东西:
void drawPyramid(const int &n) {
int b=2*n-1;
for (int i=b/2; i>=0; i--) {
for (int j=0;j<b-i; j++) {
if (i==0 || j==i || j==b-i-1) {
std::cout<<"*";
} else {
std::cout<<" ";
}
}
std::cout<<std::endl;
}
}
老的:
这样做很有趣,但它也很有效。我的方法是从金字塔末端可能具有的最大宽度开始计算,然后将问题分为两个不同的步骤:
- 转到第一个边缘
- 转到第二个边缘
它肯定可以优化,但它会给你的想法:
int drawPyramid(const int &baseWidth, const char &edgeChar, const char &outsideChar, const char &insideChar) {
// test if base width allows to have a single char at the top of it
if (baseWidth%2==0) {
std::cout<<"Error in 'drawPyramid(const int &baseWidth)': Pyramid base width must be an odd number for the top to match"<<std::endl;
return 0;
}
for (int i=baseWidth; i>=0; i-=2) { // the first edge is initially far, then gets closer
int j=0;
// Go to first edge
while (j<i/2) {
std::cout<<outsideChar;
j++;
}
std::cout<<edgeChar;
if (i==1) { // at the bottom of the pyramid
for (int k=0; k<baseWidth-1; k++) {
std::cout<<edgeChar;
}
} else if (i<baseWidth) { // test if there is a second edge to reach
// Go to second edge
while (j<baseWidth-i/2-2) {
std::cout<<insideChar;
j++;
}
std::cout<<edgeChar;
}
// Done with the current line
std::cout<<std::endl;
}
return 1;
}
希望这可以帮助 :)