C# 1-2+3-4+5...+m的几种方法

class Program
    {
        //第一种(1-2)+(3-4)+(5-6)...+m
        public static void Test(int m) {
            int z = 0;
            if (m % 2 == 0)
            {
                z = -(m / 2);
            }
            else {
                z = -(m -1) / 2  + m;
            }
            Console.WriteLine(z);
        }
        //第二种1+(-2+3)+(-4+5)+(-6+7)...+m
        public static void Test1(int m) {
            int z = 0;
            if (m%2==0) {
                z = (m - 2) / 2+1-m;
            }
            else {
                z = (m - 1) / 2 + 1;
            }
            Console.WriteLine(z);
        }
        static void Main(string[] args)
        {
            //第三种
            int z = 0;
            for (var i = 1; i < 100; i++)
            {
                if (i % 2 == 0)
                {
                    z += i;
                }
                else
                {
                    z += -i;
                }
            }
            Test(100);
            Test1(100);
            Console.WriteLine(z);
            Console.ReadLine();
        }
    }

 

posted @ 2018-07-24 17:53  猪翔heart  阅读(3964)  评论(3编辑  收藏  举报