使用 C++ 列印空心金字塔和菱形圖案的程式


在此,我們將介紹如何使用 C++ 生成空心金字塔和菱形圖案。我們可以非常輕鬆地生成實心金字塔圖案。想要使其變為空心,我們需要新增一些技巧。

空心金字塔

金字塔的第一行會列印一顆星星,最後一行將列印 n 顆星星。其他行的開頭和結尾只會列印兩顆星,這兩顆星之間會留有一些空格。

示例程式碼

#include <iostream>
using namespace std;
int main() {
   int n, i, j;
   cout << "Enter number of lines: ";
   cin >> n;
   for(i = 1; i<=n; i++) {
      for(j = 1; j<=(n-i); j++) { //print the blank spaces before star
         cout << " ";
      }
      if(i == 1 || i == n) { //for the first and last line, print the stars continuously
         for(j = 1; j<=i; j++) {
            cout << "* ";
         }
      }else{
         cout << "*"; //in each line star at start and end position
         for(j = 1; j<=2*i-3; j++) { //print space to make hollow
            cout << " ";
         }
         cout << "*";
      }
      cout << endl;
   }
}

輸出

 空心菱形

菱形的第一行和最後一行會列印一顆星星。其他行的開頭和結尾只會列印兩顆星,這兩顆星之間會留有一些空格。菱形有兩部分。上半部分和下半部分。上半部分我們需要增加空格計數,下半部分我們需要減少空格計數。此處可以使用稱為 mid 的另一個變數將行號分成兩部分。

示例程式碼

#include <iostream>
using namespace std;
int main() {
   int n, i, j, mid;
   cout << "Enter number of lines: ";
   cin >> n;
   if(n %2 == 1) { //when n is odd, increase it by 1 to make it even
      n++;
   }
   mid = (n/2);
   for(i = 1; i<= mid; i++) {
      for(j = 1; j<=(mid-i); j++) { //print the blank spaces before star
         cout << " ";
      }
      if(i == 1) {
         cout << "*";
      }else{
         cout << "*"; //in each line star at start and end position
         for(j = 1; j<=2*i-3; j++) { //print space to make hollow
            cout << " ";
         }
         cout << "*";
      }
      cout << endl;
   }
   for(i = mid+1; i<n; i++) {
      for(j = 1; j<=i-mid; j++) { //print the blank spaces before star
         cout << " ";
      }
      if(i == n-1) {
         cout << "*";
      }else{
         cout << "*"; //in each line star at start and end position
         for(j = 1; j<=2*(n - i)-3; j++) { //print space to make hollow
            cout << " ";
         }
         cout << "*";
      }
      cout << endl;
   }
}

輸出

更新於:2019-07-30

6 千+ 瀏覽次數

開啟你的 職業生涯

透過完成本課程獲取認證

開始
廣告