zoukankan      html  css  js  c++  java
  • 求给定数组中最大值和其在数组中的索引并输出

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;
    
    
    namespace _03
    {
        class Program
        {
            static void Main(string[] args)
            {
                //求给定数组中最大值和其在数组中的索引并输出
                int[] intArray = { 1, 4, 34, 23, 45, 45, 23, 78, 12, 78 };  //int数组
                List<int> index = new List<int>();//声明集合 用于存放最大值的索引
                int max = 0;//存最大值
                max = CheckMax(intArray, out  index);//调用方法查找最大值和其索引
                 Console.Write("最大值是:{0},其在数组中的索引是", max);
                foreach (int item in index)//遍历最大值所在数组的索引
                {
                    Console.Write("{0}	", item);
                }
                Console.ReadKey();
            }
            /// <summary>
            /// 找出给定int数组中最大值和最大值的索引
            /// </summary>
            /// <param name="intArray">数组</param>
            /// <param name="index">存最大值在数组中的索引</param>
            /// <returns>最大值  最大值的索引</returns>
            private static int CheckMax(int[] intArray, out List<int> index)
            {
                index = new List<int>();//为index赋初值,   注:用out修饰的参数在使用前必须对其赋值
                int max = 0;
                for (int i = 0; i < intArray.Length; i++)
                {
                    if (max < intArray[i])//如果有大于当前所得最大值,清空list,并将该值赋给max
                    {
                        index.Clear();
                        max = intArray[i];
                        index.Add(i);
                    }
                    else if (max == intArray[i])//重复最大值时,向list中添加其索引
                    {
                        index.Add(i);
                    }
                }
                return max;
            }
        }
    }
    
  • 相关阅读:
    Python3.x基础学习-静态方法和类方法
    Python3.x基础学习-@property
    Python3.x基础学习-装饰器
    SpringMVC学习(七)
    SpringMVC学习(六)
    SpringMVC学习(五)
    整合SSM(二)
    整合SSM(一)
    SpringMVC学习(四)
    SpringMVC学习(三)
  • 原文地址:https://www.cnblogs.com/dfyg-xiaoxiao/p/7213787.html
Copyright © 2011-2022 走看看