交换int数组 [英] Swap in a int array
问题描述
嗨
即将交换我的arry whit中的第一个int。
Hi
im going to swap the first int in my arry whit the last.
int[] Tal = new int[10];
Console.WriteLine("10 numbers: ");
for (int i = 0; i < Tal.Length; i++)
{
Console.Write("number " + (i + 1) + ": ");
Tal[i] = int.Parse(Console.ReadLine());
}
Arra c = new Array();
c.FirstLast(Tal)
public void FirstLast(int[] arr)
{
foreach (int t in arr)
{
int temp = arr[0];
arr[0] = arr[9];
arr[9] = temp;
Console.WriteLine(t);
}
当我输入1,2,3,4,5,6,7时,
, 8,9,10然后它显示1,2,3,4,5,6,7,8,9,1
i希望它是10,2,3,4,5, 6,7,8,9,1。我知道我替换了第一个最后一个但是它没有取代第一个最后一个。
抱歉英语不好。我希望有人能理解
when i type in 1,2,3,4,5,6,7,8,9,10 and then it show 1,2,3,4,5,6,7,8,9,1
i want it to be 10,2,3,4,5,6,7,8,9,1. I know i replace the first whit the last but way dos it not replace the first one to whit the last.
sorry for the bad english. I hope someone will understand it
推荐答案
试试这个:
Hi,
Try this:
public void SwapFirstAndLast(ref int[] array)
{
int temp = array[0];
int posOfLast = array.Length - 1;
array[0] = array[posOfLast];
array[posOfLast] = temp;
}
如何使用此交换方法:
How to use this swap method:
SwapFirstAndLast(ref intArray); // change intArray into the name of your array
关于 ref
关键字的更多信息: http: //msdn.microsoft.com/en-us/library/14akc2c7.aspx [ ^ ]
希望这会有所帮助。
More about the ref
keyword: http://msdn.microsoft.com/en-us/library/14akc2c7.aspx[^]
Hope this helps.
你应该采取来自foreach循环的交换代码:
You should probably take the swapping code out from the foreach loop:
public void FirstLast(int[] arr)
{
int temp = arr[0];
arr[0] = arr[9];
arr[9] = temp;
foreach (int t in arr)
{
Console.WriteLine(t);
}
}
并且,肯定是使用 ref
在函数调用中交换值,以便您可以在控制台,窗口中显示结果,或者我知道可能在另一个函数中返回值。
Happy编码。
And, yes definitely use ref
in function call that swaps the values so that you can show your result in console, window or what do I know maybe return as value in another function.
Happy coding.
int j = 9;
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] arr2 = new int[10];
for (int i = 0; i < arr.Length; i++)
{
arr2[j--] = arr[i];
Console.WriteLine(arr2[i]);
}
for (int i = 0; i < arr2.Length; i++)
{
Console.WriteLine(arr2[i]);
}
Console.ReadKey();
这篇关于交换int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!