首页 > 解决方案 > 将数组中的所有整数相乘

问题描述

我需要将给定数组中的所有整数乘以-1。我没有看到我在哪里犯了错误,但这是我到目前为止的代码:

public static int[] InvertValues(int[] input)
{
int x = -1;
  foreach(int y in input)
   { 
    x *= y;
  }
    return input;
}

标签: c#arraysmath

解决方案


这是基于作者最初尝试的一种解决方案:

这会将每个单个元素乘以 -1。

您的错误是您需要访问数组的每个单独元素并通过索引将其写回。为此,您最好使用for循环。

然后访问输入数组中的原始值,将其乘以 -1 并将其写回,从而覆盖输入数组中的原始值。

public static int[] InvertValues(int[] input)
{

  for(int index = 0; index<input.Length;index++)
  { 
    input[index] = input[index] * -1;
  }
  
  return input;
}

我会进行下一步,而不是更改原始输入数组并返回一个副本:

public static int[] InvertValues(int[] input)
{
  int[] results = new int[input.Length]

  for(int index = 0; index<input.Length;index++)
  { 
    results [index] = -input[index]; //this flips the sign of the number, no need to do * -1
  }
  
  return results;
}

一个更好更短的选择:)

using System.Linq; //need to be added

//...

public static int[] InvertValues(int[] input)
{
  return input.Select(x=> -x).ToArray();
}

推荐阅读