比较两个int数组

时间:2014-10-26 17:56:00

标签: c#

我写了这段代码:

class Program
{
    static void Main(string[] args)
    {
        Test t = new Test();
        int[] tal1 = { 3, 2, 3};
        int[] tal2 = { 1, 2, 3};

        Console.WriteLine(t.theSameInBoth(tal1,tal2));
    }
}

class Test
{
    public Boolean theSameInBoth(int[] a, int[] b)
    {
        bool check = false;

        if (a.Length == b.Length)
        {
            for (int i = 0; i < a.Length; i++)
                if (a[i].Equals(b[i]))
                {
                    check = true;
                    return check;
                }
        }

        return check;
    }
}

所以这里的交易是。我需要发送两个带有数字的数组。然后我需要通过检查数组。如果数组中的所有数字都相同。我需要将支票设置为true并将其返回。唯一的问题是。使用我在这里设置的代码,我发送了一个带有3,2,3的数组和一个带有1,2,3的数据,它仍然将检查返回为真。

我是这里的新手,所以我希望这里的任何人都可以帮助我!

4 个答案:

答案 0 :(得分:3)

您需要撤消测试:

class Test
{
    public bool theSameInBoth(int[] a, int[] b)
    {
        if (a.Length == b.Length)
        {
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] != b[i])
                {
                    return false;
                }
            }

            return true;
        }

        return false;
    }
}

只要一对项目不同,两个数组就不同了。

在您的代码中,您有效地说,只要一对项目相等,两个数组就相等。

答案 1 :(得分:1)

一旦找到第一场比赛,你就会回来。你需要这样的东西:

bool check = true;

if (a.Length == b.Length)
{
   for (int i = 0; i < a.Length; i++)
   {
      if (!a[i].Equals(b[i]))
      {
            check = false;
            break;
       }

   }
   return check;
}
else 
  return false;

答案 2 :(得分:1)

bool isIndentical = true;

if (a.Length == b.Length)
{
    for (int i = 0; i < a.Length; i++)
         if (!a[i].Equals(b[i]))
         {
            isIndentical = false;
            return check;
         }
}

return isIndetical;

试试这样。您的代码始终返回true,因为如果数组中的某个元素相等,则if语句中的代码将返回true。在我的情况下,我检查不相等,如果发生这种情况,只需返回false。看到我使用其他变量,这使得它更清晰,并在乞讨中使其成为现实。

答案 3 :(得分:0)

我的习惯是添加Linq解决方案:

public bool IsSame(int[] a, int[] b)
{
    return a.Length == b.Length &&
           a.Select((num, index) => num == b[index]).All(b => b);
}

另一个很酷的Linq方法:

public bool IsSame(int[] a, int[] b)
{
    return a.Length == b.Length &&
           Enumerable.Range(0, a.Length).All(i => a[i] == b[i]);
}
相关问题