gpt4 book ai didi

c# - x 数组中的重复元素添加到 y 数组中

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:47 24 4
gpt4 key购买 nike

我试图从数组 x 中找到 2 个或更多相同的元素,然后将其复制并添加到新数组 Y 中

所以如果我在 x 数组中有这样的数字:2,5,7,2,8 我想将数字 2 添加到 y 数组中

int[] x = new int[20];
Random rnd = new Random();
int[] y = new int[20];
int counter = 0;


for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 15);

for (int j=i+1; j< x.Length; j++)
{
if (x[i] == x[j])
{

y[counter] = x[i];
Console.WriteLine("Repeated numbers are " + y[counter]);
counter++;
}
else
{
Console.WriteLine("There is no repeated numbers, numbers that are in x are " + x[i]);
}
break;
}
}

但是有问题,当涉及到 if 循环时,它不想继续执行 if 循环(即使条件为真)

如果有人能给我一些建议,那会很有帮助,谢谢

最佳答案

您对for 的使用存在各种逻辑错误。您应该更多地关注您的逻辑,因为虽然可以死记硬背地学习库,但逻辑错误更多是您内心深处的东西。

int[] x = new int[20];
Random rnd = new Random(5);

// You don't know the length of y!
// So you can't use arrays
List<int> y = new List<int>();

// First initialize
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 15);
}

// Then print the generated numbers, otherwise you won't know what numbers are there
Console.WriteLine("Numbers that are in x are: ");
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}

// A blank line
Console.WriteLine();

// Then scan
for (int i = 0; i < x.Length; i++)
{
for (int j = i + 1; j < x.Length; j++)
{
if (x[i] == x[j])
{
y.Add(x[i]);
Console.WriteLine("Repeated numbers is " + x[i]);
}
}
}

// Success/failure in finding repeated numbers can be decided only at the end of the scan
if (y.Count == 0)
{
Console.WriteLine("There is no repeated numbers");
}

我在代码中添加了一些注释(加上更改)

出于调试目的,我建议您使用固定的 Random 序列。 new Random(5)(或任何其他数字)将在您每次启动程序时返回相同的序列。

请注意,如果一个数字有多次重复,例如 { 4, 4, 4 } 那么 y 数组将为 { 4, 4 }

关于c# - x 数组中的重复元素添加到 y 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50522966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com