How can we get the middle element in an array?
Example code:
string[] source = txtInput.Text.Split(',');
开发者_开发知识库int[] nums = new int[input.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
int first=nums[0];
int mid=///how is it?
Like this:
int mid = nums[nums.Length/2];
You take the size of the array (nums.Length
), divide by two to get the index in the middle and use that index.
int mid = nums[nums.Length / 2];
Since it is all ints the number will be rounded down if Length is odd.
mid = input.Lenght/2
Get the middle index and then return the element at that middle index:
int [] arr = {1,2,3,4,5,6,7}
int middIndex = arr.Length / 2;
Console.WriteLine(arr[middIndex]);
the total number of elements devided by 2 gives the middle element:
int mid = nums[Convert.ToInt32(num.Count /2)];
精彩评论