[英]Compare two int arrays
我寫了這段代碼:
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的數組,它仍然將check檢查為true。
我是這里的新手,所以我希望這里的任何人都可以幫助我!
你需要反轉測試:
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;
}
}
只要一對項目不同,兩個數組就不同了。
在你的代碼中,你有效地說,只要一對項目相等,兩個數組是相等的。
你找到第一場比賽后就會回來。 你需要這樣的東西:
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;
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
。 看到我使用其他變量,這使得它更清晰,並在乞討中使其成為現實。
我的習慣是添加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]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.