在 C++ 中列印金字塔


本文使用 C++ 程式設計程式碼生成了“類金字塔結構”的輸出。其中,金字塔的高度和間隔由遍歷雙重 for 迴圈構造來決定,如下所示;

示例

 線上演示

#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;
}

輸出

在編譯完上述程式碼後,將列印類似如下內容的金字塔。

         *
       * * *
     * * * * *
   * * * * * * *
 * * * * * * * * *
* * * * * * * * * * *

更新於: 2019 年 12 月 23 日

347 次瀏覽

開啟您的 職業之旅

完成課程即可獲得認證

開始
廣告