1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication7 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 int sum = Test(1, 2, 3, 4, 5); 14 Console.WriteLine("多个整数之和为:{0}", sum); 15 Console.ReadKey(); 16 } 17 18 static int Test(params int[] arr) 19 { 20 int sum = 0; 21 for (int i = 0; i < arr.Length; i++) 22 { 23 sum += arr[i]; 24 } 25 return sum; 26 } 27 } 28 }
改进后:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication7 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 14 Console.WriteLine("请输入需要相加的整数个数"); 15 int i = Convert.ToInt32(Console.ReadLine()); 16 int[] readint = new int[i]; 17 for (int k = 0; k < i; k++) 18 { 19 Console.WriteLine("请输入需要相加的整数"); 20 readint[k] = Convert.ToInt32(Console.ReadLine()); 21 } 22 int sum = Test(readint); 23 Console.WriteLine("多个整数之和为:{0}", sum); 24 Console.ReadKey(); 25 } 26 27 static int Test(params int[] arr) 28 { 29 int sum = 0; 30 for (int i = 0; i < arr.Length; i++) 31 { 32 sum += arr[i]; 33 } 34 return sum; 35 } 36 } 37 }