C# 十種不同的數字模式 - 弗洛伊德的三角形(Floyd's Triangle)

  • 3022
  • 0
  • C#
  • 2017-03-23

內容引述 http://www.csharpstar.com/10-different-number-pattern-programs-in-csharp/

第六種 弗洛伊德的三角形(Floyd's Triangle)

輸出結果如下圖:

整理概念如下:

1 row   = 1,

2 rows = 1,23,

3 rows = 1,23,456,

4 rows = 1,23,456,78910

把數字抽掉會變成如下:

1 row   = _,

2 rows = _,_ _,

3 rows = _,_ _,_ _ _,

4 rows = _,_ _,_ _ _,_ _ _ _,

其實很常用的 i , j 迴圈便已是此格式

for (int i = 1; i <= rows; i++)
      for (int j = 1; j <= i; j++)

所以再加上個計算數字累加的值 ( num ) 便可達成。

using System;

namespace Pattern6
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.Write("請輸入行數 : ");

                int rows = Convert.ToInt32(Console.ReadLine());
                int num = 1;

                for (int i = 1; i <= rows; i++)
                {
                    for (int j = 1; j <= i; j++)
                    {
                        Console.Write( num + " ", num++ );
                    }
                    Console.Write("\n");
                }
            }
        }
    }
} 

 

本頁面為一點點累積學習寫程式之路。

許多資訊不是正確、或只是自己看的懂得。

如果不小心點進來誤導了您,還真的不好意思。