首页 > 其他 > 详细

写一方法计算实现任意个整数之和.在主调函数中调用该函数,实现任意个数之和。(使用params参数)

时间:2015-12-19 00:10:17      阅读:222      评论:0      收藏:0      [点我收藏+]

 

 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 }

 

写一方法计算实现任意个整数之和.在主调函数中调用该函数,实现任意个数之和。(使用params参数)

原文:http://www.cnblogs.com/start-from-scratch/p/5058409.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!