文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>思维体操:用c#简单实现按一定规则输出有序数列

思维体操:用c#简单实现按一定规则输出有序数列

时间:2010-09-15  来源:Jeff Wong

要求:输入一个整数num,打印出如下规则的一组数字:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
... ...

比如输入数字7,应该有如下输出:

1
2 3
4 5 6

下面是用c#的简单实现:

代码         public static void Print(int num)
        {
            int counter = 1;
            for (int i = 0; i < num; i++)
            {
                StringBuilder sb = new StringBuilder(100);
                for (int j = 0; j < i + 1; j++)
                {
                    int output = j + counter;

                    sb.AppendFormat("{0}  ", output);
                    if (j == i)
                    {
                        counter = output + 1;//下一行的第一个数字是前一行的最后一个加1
                    }
                    if (output == num)
                    {
                        counter = num;//是最后一个数字 跳出循环
                        break;
                    }
                }
                Console.WriteLine(sb.ToString());
                if (counter == num)
                {
                    return;
                }
            }

        }

        static void Main(string[] args)
        {
            Print(1);
            Console.WriteLine("--------------");

            Print(7);
            Console.WriteLine("--------------");

            Print(10);
            Console.WriteLine("--------------");

            Print(15);
            Console.WriteLine("--------------");

            Print(30);
        }

分析上面的代码,我个人认为这是最简单明了符合常规认知的一种实现:要输出有序序列的数字,找出数字排列的规律,找到这个规律,最后就是水到渠成的编程实现罢了。
最后卖个关子,其实它还有一种代码更加简洁的实现,是从某高手那里偷师的,大家不妨动手练习一下吧,这个还是很能考验一个人的逻辑思维的。

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载