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

    运行结果为:

  • 相关阅读:
    POJ 1611
    [Erlang24]使用zotonic搭建网站记录
    [Erlang23]怎么有效的遍历ETS表?
    [Erlang22]如何按规则位数输出数字
    [Git00] Pro Git 一二章读书笔记
    十分钟用HTML&CSS让博客园变得高大上
    [Erlang21]Erlang性能分析工具eprof fporf的应用
    [Erlang20]一起攻克Binary
    [Erlang19]Erlang的config文件读取效率问题
    [Erlang18]教练!又发现Erlang Shell里面的神奇函数一只
  • 原文地址:https://www.cnblogs.com/zhoukaiwei/p/2277971.html
Copyright © 2011-2022 走看看