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

 

 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 }

 

转载于:https://www.cnblogs.com/start-from-scratch/p/5058409.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值