一首简单的数字加减算法题
求 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; } }