3 回答
TA贡献1789条经验 获得超8个赞
我的方法遵循许多人的思路。为了简单起见,我使用了 LINQ。
int fullProduct = 1;
List<int> input = new List<int> { 2, 3, 6, 8 };
List<int> result = new List<int>();
input.ForEach(v => { fullProduct *= v; });
input.ForEach(c=>
{
result.Add(fullProduct / c);
});
TA贡献1828条经验 获得超3个赞
使用 Linq 执行此操作的一种方法是使用Aggregate获取值的总乘积,然后将结果值分配为等于乘积除以当前循环索引处的输入项:
static void Multiply()
{
int[] input = { 2, 3, 6, 8 };
int[] result = new int[input.Length];
var product = input.Aggregate((i, j) => i * j);
for (int i = 0; i < input.Length; i++)
{
result[i] = product / input[i];
}
Console.WriteLine(string.Join(" ", input));
Console.WriteLine(string.Join(" ", result));
Console.ReadKey();
}
输出

TA贡献1770条经验 获得超3个赞
class Program
{
static int GetMulResult(int[] input, int ommitingIndex)
{
int result = 1;
for(int i = 0; i < input.Length; i++)
{
if (i == ommitingIndex)
continue;
result *= input[i];
}
return result;
}
static void Main(string[] args)
{
int[] inputArray = { 2, 3, 6, 8 };
int[] result1 = new int[4];
for(int i = 0; i < inputArray.Length; i++)
result1[i] = GetMulResult(inputArray, i);
}
}
PS。恐怕如果你不能创建这样一个简单的算法,你将无法创建更多可用的算法。你应该为此努力。
- 3 回答
- 0 关注
- 159 浏览
添加回答
举报
