我有一个问题,请帮助我创建2 array
s
1)偶数数组
2)奇数数组
在标签中我看到一切都好。数组很好。但它们并没有像我预期的那样被创造出来。
和数组2
我的数组代码是
for (indexi = 2; indexi < masivi1.Length; indexi = indexi + 2)
{
masivi1[indexi] = indexi;
}
for (k = 2; k < masivi1.Length; k = k + 2)
{
label2.Text += masivi1[k].ToString;
}
第二个数组
for (indexi1 = 0; indexi1 < masivi2.Length; indexi1++)
{
if (indexi1 % 2 != 0)
{
masivi2[indexi1] = indexi1;
}
}
for (k1 = 0; k1 < masivi2.Length; k1++)
{
if (k1 % 2 != 0)
{
label3.Text += masivi2[k1].ToString() + " | ";
}
}
有人可以帮助显示正确创建数组的解决方案
2,4,6 ...
1,3,5 ...
答案 0 :(得分:2)
你可以用这样的奇数,偶数来填写两个数组
var evenArray = new int[10];
var oddArray = new int[10];
for (int i = 0, even = 0; i < evenArray.Length; i++, even += 2)
{
evenArray[i] = even;
}
for (int i = 0, odd = 1; i < oddArray.Length; i++, odd += 2)
{
oddArray[i] = odd;
}
可生产
evenArray = [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18 ]
oddArray = [ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 ]
答案 1 :(得分:1)
不确定你想要实现的目标,但这看起来不对:
for (indexi = 2; indexi < masivi1.Length; indexi = indexi + 2)
{
masivi1[indexi] = indexi;
}
因为你只是在每个第二个数组元素中加入一些东西,即2,4,6,......
也许这就是你想要的:
for (indexi = 0; indexi < masivi1.Length; ++indexi)
{
masivi1[indexi] = 2*indexi + 2;
}
第二个阵列有同样的问题:
for (indexi1 = 0; indexi1 < masivi2.Length; indexi1++)
{
if (indexi1 % 2 != 0) // This line means that you only put
// elements in the array when index1 = 1, 3, 5, ...
{
masivi2[indexi1] = indexi1;
}
}
答案 2 :(得分:1)
for (int indexi = 0; indexi < masivi1.Length && indexi < masivi2.Length; ++indexi)
{
if (indexi % 2 == 0)
{
masivi1[indexi / 2] = indexi;
}
else
{
masivi2[indexi / 2] = indexi;
}
}