求给定数组中最大值和其在数组中的索引并输出

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}\t", 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;
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值