求1-100所有整数和:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 int sum= GetSum(1,100); 6 Console.WriteLine("1-100之间所有整数和{0}",sum); 7 Console.ReadKey(); 8 } 9 /// <summary> 10 /// 1-100之间的所有整数和 11 /// </summary> 12 /// <param name="p1"></param> 13 /// <param name="p2"></param> 14 /// <returns></returns> 15 private static int GetSum(int p1, int p2) 16 { 17 int sum = 0; 18 for (int i = p1; i <= p2; i++) 19 { 20 sum += i; 21 } 22 return sum; 23 24 } 25 }
两种方案:
1.通过for遍历
2.通过while遍历