Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在我的算法中,查找一个和除以k的数组中的所有对的缺陷在哪里?_C#_Algorithm_Linq - Fatal编程技术网

C# 在我的算法中,查找一个和除以k的数组中的所有对的缺陷在哪里?

C# 在我的算法中,查找一个和除以k的数组中的所有对的缺陷在哪里?,c#,algorithm,linq,C#,Algorithm,Linq,我搞不清楚我做错了什么 代码: using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static void Main(String[] args) { string[] lineParts = Console.ReadLine().Split(' '); int k = Convert.ToInt3

我搞不清楚我做错了什么

代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
    static void Main(String[] args) 
    {
        string[] lineParts = Console.ReadLine().Split(' ');
        int k = Convert.ToInt32(lineParts[1]);
        int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
        var indices = Enumerable.Range(0, arr.Length - 1);
        int pairsDivideK = (from i in indices
                            from j in indices
                            where i < j && ((arr[i] + arr[j]) % k == 0)
                            select 1).ToList().Count / 2;
        Console.WriteLine(pairsDivideK);
    }
}
预期产出:

5
我的输出:

1

首先,你不必除以2。由于i 第二个:必须使用Enumerable.Range0,arr.Length no-1作为第二个参数,它不是上限,而是元素的计数

因此,您的代码应该是:

...
var indices = Enumerable.Range(0, arr.Length);
int pairsDivideK = (from i in indices
                    from j in indices
                    where i < j && ((arr[i] + arr[j]) % k == 0)
                    select 1).ToList().Count;
Console.WriteLine(pairsDivideK);

选择1.ToList.Count/2为什么要这样做?@user3185569我要除以2来计算重复次数,为什么我应该小于j?为什么不使用linesParts中的第一个值,即6?你能至少解释一下你为什么要做每一步吗?你已经用i... var indices = Enumerable.Range(0, arr.Length); int pairsDivideK = (from i in indices from j in indices where i < j && ((arr[i] + arr[j]) % k == 0) select 1).ToList().Count; Console.WriteLine(pairsDivideK);