在C ++中打印金字塔
本文使用C++编程代码生成“金字塔状结构”作为输出。其中金字塔高度和空间是通过遍历doublefor循环构造确定的,如下所示;
示例
#include <iostream>
using namespace std;
int main() {
int space, rows=6;
for(int i = 1, k = 0; i <= rows; ++i, k = 0){
for(space = 1; space <= rows-i; ++space){
cout <<" ";
}
while(k != 2*i-1){
cout << "* ";
++k;
}
cout << endl;
}
return 0;
}输出结果
编译完上面的代码后,金字塔的外观将如下所示。
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *