【问题标题】:C# how do I use a partially filled array in a method?C# 如何在方法中使用部分填充的数组?
【发布时间】:2017-04-03 13:19:20
【问题描述】:

我的导师希望我们创建一个包含 10 个元素的数组,然后使用控制台输入用随机数填充它,然后将所有数字相乘以获得乘积。我不知道如何将数组传递给方法,然后成功获取产品。我是否使用 for 循环?我认为我不能使用 foreach 循环,因为它可能会被部分填充。我如何首先将数组传递给方法?

这是我迄今为止将值存储在数组中的内容。

for (int i = 0; i < SIZE; i++)
{

    bool valid = false;
    do
    {
         Write("Enter an integer value or 0 to stop ");
         string input = ReadLine();
         valid = int.TryParse(input, out userInput);
    } while (!valid);

    if (userInput == 0)
    {
         break;
    }
    array[i] = userInput;
}

product = p.ArrayProduct(array.Length);

【问题讨论】:

  • 您可以像传递任何其他对象一样传递数组。在 C# 中,数组长度信息由数组本身携带,因此您不需要在额外的参数中传递长度(这与 C 不同)。一个电话可能看起来像product = mutiplyElems(array);。你也可以看看 linq 能为你做什么,但对于初学者来说有点神秘。
  • 要处理部分使用的数组,您必须创建单独的变量来跟踪用户输入了多少项目。然后,您必须将该值与数组一起传递给任何进行处理的方法,以便他们知道要使用数组的多少个槽。
  • 我该怎么做?
  • 听起来你真的应该使用List&lt;int&gt;而不是int[],随着新项目的添加,它会增长。
  • 附带说明,获取产品不需要将数字存储在集合中,但任务似乎是让您熟悉数组的基础知识(即使它们很少用于高级 C#)

标签: c# arrays


【解决方案1】:

乘法如下:

public int ArrayProduct(int[] array)
{
   int p = 1;
   for(int i = 0; i < array.Length; i++)
   {
       p *= array[i];
   }
   return p;
}

您也可以在foreach 循环中相乘:

public int ArrayProduct(int[] array)
{
   int p = 1;
   foreach(int element in array)
   {
       p *= element;
   }
   return p;
}

或者您可以使用Array 类,如下所示:

public int ArrayProduct(int[] array)
{
    int p = 1;
    Array.ForEach(array, el =>
    {
        p *= el;
    });
    return p;
}

还有另一种用于数组的扩展方法,你猜怎么着! ForEach

public int ArrayProduct(int[] array)
{
    int p = 1;
    array.ForEach(element =>
    {
        p *= element;
    });
    return p;
}

然后你得到如下数据后调用它:

int product = ArrayProduct(array);
Console.WriteLine(product);

@Peter A. Schneider 根据这个问题here 使用Linq 说还有另一种方式@

public int ArrayProduct(int[] array)
{
    return array.Aggregate(1, (acc, val) => acc * val);
}

c# 6 及以上更好:

public int ArrayProduct(int[] array) => array.Aggregate(1, (acc, val) => acc * val);

如果您在获取数据时遇到问题,请告诉我!

【讨论】:

  • 该代码返回的值为 0,我不知道为什么。
  • 您是否设置了 p = 1 的值而不是 0 ?或者您可能输入了一个值 0,这将使结果乘以 0
  • @EvanGlassford 你可以把p *= el;改成if (el != 0) p *= el;
  • @Slai 但这将不再计算数组元素的乘积;-)。
  • 为了完整起见,您可以在stackoverflow.com/a/252343/3150802 中提及array.Aggregate(1, (acc, val) =&gt; acc * val);
【解决方案2】:

这是一个跟踪单独变量中的条目数并将其与数组一起传递给处理函数的示例:

static void Main(string[] args)
{
    int SIZE = 10;
    int numEntries = 0;
    int[] array = new int[SIZE];

    Console.WriteLine("Enter up to " + SIZE.ToString() + " integer(s).");

    string input;
    int userInput;
    for (int i = 0; i < array.Length; i++)
    {
        bool valid = false;
        do
        {
            Console.Write("Enter integer #" + (i+1).ToString() + " or 0 to stop: ");
            input = Console.ReadLine();
            valid = int.TryParse(input, out userInput);
            if (!valid)
            {
                Console.WriteLine("Invalid entry!");
            }
        } while (!valid);

        if (userInput == 0)
        {
            break;
        }

        numEntries++;
        array[i] = userInput;
    }

    if (numEntries > 0)
    {
        int product = ArrayProduct(array, numEntries);
        Console.WriteLine("The product is " + product.ToString("n0") + ".");
    }
    else
    {
        Console.WriteLine("No entries were made!");
    }

    Console.Write("Press [Enter] to quit.");
    Console.ReadLine();
}

private static int ArrayProduct(int[] arr, int length)
{
    int product = 1;
    if (length <= arr.Length)
    {
        for(int i = 0; i < length; i++)
        {
            product = product * arr[i];
        }
    }
    return product;
}

【讨论】:

    【解决方案3】:

    您可以通过引用调用方法。您应该使用 from out 和 ref 关键字: https://msdn.microsoft.com/en-us/library/t3c3bfhx.aspx

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      相关资源
      最近更新 更多