一首简单的数字加减算法题

求 1-2+3-4+...m 的值?

View Code
static void Main(string[] args)
        {
            int result = Sum(5);
            Console.WriteLine(result.ToString());
        }

        public static int Sum(int num)
        {
            if (num.Equals(0) || num.Equals(1))
            {
                return num;
            }
            else
            {
                int sum = 0;
                for (int i = 1; i < num; i++)
                {
                    if ((i % 2) == 1)
                        sum += i;
                    else
                        sum -= i;
                }

                return sum;
            }
        }

 

posted @ 2013-04-27 22:26  Binyao  阅读(183)  评论(0编辑  收藏  举报