C++三角形圖案程式(圍繞0的對稱影像)


假設有一個正數值n,任務是生成一個三角形圖案,即列印數字的對稱影像並顯示結果

範例

Input-: n = 6
Output-:

Input-: n = 3
Output-:

以下程式採用的方法如下

  • 輸入n的值,作為正整數
  • 遍歷一個i迴圈,作為模式中的行數,即n
  • 遍歷一個j迴圈,作為模式中的空格數
  • 遍歷另一個迴圈,作為模式中的數字

演算法

START
Step 1-> declare function to print mirror image of triangular pattern
   void print_mirror(int n)
   declare and set int temp = 1 and temp2 = 1
      Loop for int i = 0 and i < n and i++
         Loop For int j = n - 1 and j > i and j—
            print space
         End
         Loop For int k = 1 and k <= temp and k++
            print abs(k - temp2)
         End
         Set temp += 2
         increment temp2++
         print \n
Step 2-> In main()
   Declare int n = 6
   print_mirror(n)
STOP

範例

#include <bits/stdc++.h>
using namespace std;
//function to print mirror image of triangular pattern
void print_mirror(int n) {
   int temp = 1, temp2 = 1;
   for (int i = 0; i < n; i++) {
      for (int j = n - 1; j > i; j--) {
         cout << " ";
      }
      for (int k = 1; k <= temp; k++) {
         cout << abs(k - temp2);
      }
      temp += 2;
      temp2++;
      cout << "\n";
    }
}
int main() {
   int n = 6;
   print_mirror(n);
   return 0;
}

輸出

更新於: 2020年7月9日

268次瀏覽

推動你的 職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.