zoukankan      html  css  js  c++  java
  • 参数数组

              参数数组
            

            定义一个函数,用采取得的数字的和,但是数字的个数不确定。

            解决方案:

            可以使用一个参数数组来进行求解:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace 参数数组
     8 {
     9     //求一串数字的和
    10 
    11     class Program
    12     {
    13         //方法1
    14         static int Sum(int[] arrays)
    15         {
    16             int sum = 0;
    17             for (int i = 0; i < arrays.Length; i++)
    18             {
    19                 sum += arrays[i];
    20             }
    21             return sum;
    22         }
    23 
    24         //方法2
    25         static int Plus(params int[] arrays)
    26         {
    27             int sum = 0;
    28             for(int i=0;i<arrays.Length;i++)
    29                 sum+=arrays[i];
    30             return sum;
    31         }
    32 
    33         static void Main(string[] args)
    34         {
    35             int sum = Sum(new int[] { 12, 321, 34, 12, 3, 12 });
    36             Console.WriteLine(sum);
    37 
    38             int sum2 = Plus(213,32,123,,321321,32);
    39             Console.WriteLine(sum2);
    40 
    41 
    42             Console.ReadKey();
    43         }
    44     }
    45 }

            除了参数数组,所有函数的参数都是固定的,在调用参数数组的时候,参数一定要传递,否则会出错。

            参数数组和数组参数的不同:在于函数的调用,参数数组在调用函数的时候,我们可以传递过来任意多个参数,然后编译器会帮我们自动组拼成一个数组,参数如果是上面的数组参数那么这个数组需要我们手动去创建。

  • 相关阅读:
    架设WCF项目出现的问题
    百思不得其解的"Failed to allocate a managed memory buffer of 268435456 bytes."错误解决
    Ajax 分页
    关于Asp.net调用外部程序的拒绝访问错误
    转贴:[翻译]Visual Studio 2008 Code Metrics
    荀子,劝学篇(部分)
    .net设计模式(转载)
    人月神话读书笔记
    Memory food
    2010年4月12日,今天做计划
  • 原文地址:https://www.cnblogs.com/jc-1997/p/6070584.html
Copyright © 2011-2022 走看看