zoukankan      html  css  js  c++  java
  • C#数组的用法,out传递值的用法

    从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;
    }
    }
    }

    运行结果为:

  • 相关阅读:
    2101 可达性统计
    POJ1179 Polygon
    POJ1015 Jury Compromise
    读入输出优化
    队列优化dijsktra(SPFA)的玄学优化
    5104 I-country
    CH5102 Mobile Service
    P1005 矩阵取数游戏
    (模板)线段树2
    POJ3666 Making the Grade
  • 原文地址:https://www.cnblogs.com/zhoukaiwei/p/2277971.html
Copyright © 2011-2022 走看看