• 写一方法计算实现任意个整数之和.在主调函数中调用该函数,实现任意个数之和。(使用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 }
  • 相关阅读:
    202011.19
    202011.18
    202011.17
    202011.16
    202011.14
    jdk的下载和配置
    layui中form表单
    JS中utocomplete
    转:JqueryUI学习笔记-自动完成autocomplete
    JSON.parse()与JSON.stringify()的区别
  • 原文地址:https://www.cnblogs.com/start-from-scratch/p/5058409.html
Copyright © 2020-2023  润新知