c# - 比较两个 int 数组

标签 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 的数组,它仍然返回检查为真。

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

最佳答案

你需要逆向测试:

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;
    }
}

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

在您的代码中,您实际上是说只要一对项目相等,两个数组就相等。

关于c# - 比较两个 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26576111/

相关文章:

c# - 如何知道编译时错误代码?

c# - TreeView 详细架构问题

c# - 在 WPF 中,您可以在没有代码隐藏的情况下过滤 CollectionViewSource 吗?

c# - 如何在没有 Auth 的情况下连接到 YouTube API?

c# - 如何在 C# 中以编程方式将 xlsx 文件转换为 2003 xls 文件?

c# - 如何使用表达式树对数字类型应用隐式转换?

c# - 当 DataGridView.SelectionMode 为 FullRowSelect 时剪贴板复制失败

c# - ocelot api网关中的System.InvalidOperationException

c# - 使用除系统数据库之外的数据库名称填充下拉列表

c# - 如何在datagridview中显示图片? C#