坚持139

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

从C#入门经典中摘的一个例子,从一个数组中,找出最大值,并记录最大值在数组中的位置。由于最大值有相同的,所以将位置存在一个数组中,通过out传递。

数组为 int[] testArray = { 4, 7, 4, 2, 7, 3, 7, 8, 3, 9, 1, 9 }; 最大值为9,储存位置为9和11。

使用debug.writeline,将调试结果显示在中断模式的output窗口中。

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Ch07Ex01
{
class Program
{
static void Main(string[] args)
{
int[] testArray = { 4, 7, 4, 2, 7, 3, 7, 8, 3, 9, 1, 9 };
int[] maxValIndices;
int maxVal = Maxima(testArray, out maxValIndices);
Console.WriteLine("Maximum value {0} found at element indices:",
maxVal);
foreach (int index in maxValIndices)
{
Console.WriteLine(index);
}
Console.ReadKey();
}

static int Maxima(int[] integers, out int[] indices)
{
Debug.WriteLine("Maximum value search started.");
indices = new int[1];
int maxVal = integers[0];
indices[0] = 0;
int count = 1;
Debug.WriteLine(string.Format(
"Maximum value initialized to {0}, at element index 0.", maxVal));
for (int i = 1; i < integers.Length; i++)
{
Debug.WriteLine(string.Format("Now looking at element at index {0}.",
i));
if (integers[i] > maxVal)
{
maxVal = integers[i];
count = 1;
indices = new int[1];
indices[0] = i;
Debug.WriteLine(string.Format(
"New maximum found. New value is {0}, at element index {1}.",
maxVal, i));
}
else
{
if (integers[i] == maxVal)
{
count++;
int[] oldIndices = indices;
indices = new int[count];
oldIndices.CopyTo(indices, 0);
indices[count - 1] = i;
Debug.WriteLine(string.Format(
"Duplicate maximum found at element index {0}.", i));
}
}
}
Trace.WriteLine(string.Format(
"Maximum value {0} found, with {1} occurrences.", maxVal, count));
Debug.WriteLine("Maximum value search completed.");
return maxVal;
}
}
}

运行结果为:

posted on 2011-12-06 14:35  坚持139  阅读(1931)  评论(0编辑  收藏  举报