您的位置:首页 > 其它

.NET中,写一个函数找出一个整数数组中,第二大的数(整数数组作为函数参数)

2013-04-19 22:39 302 查看
static void Main(string[] args)
{
int[] nums = { 1, 2, 10, 1, 5, 5, 3, 101, 11, 12, -1, 12 };
int secmax = SecNum(nums, nums.Length);
#region 数组不做参数时,直接在主函数中写
//int max = nums[0];
////int secmax = -1;
//for (int i = 0; i < nums.Length; i++)
//{
//    //如果nums[i]大于最大数,那么就更新第二大数和最大数
//    if (nums[i] > max)
//    {
//        secmax = max;
//        max = nums[i];
//    }
//    else if (nums[i]>secmax)//当第二大的数字在最大的数后边时,上边的方法就不行了,必须加这个
    //                            //如果nums[i]大于第二大的数 且小于最大数时 只更新第二大数就可以了
//    {
//        secmax = nums[i];
//    }
//}
//Console.WriteLine("最大的数是:{0}",nums.Length);
#endregion
Console.WriteLine("第二大的数是:{0}",secmax);
Console.ReadKey();
}

private static int SecNum(int[] nums, int length)
{
int max = nums[0];
int secmax = -1;
for (int i = 0; i < length; i++)
{
//如果nums[i]大于最大数,那么就更新第二大数和最大数
if (nums[i] > max)
{
secmax = max;
max = nums[i];
}
else if (nums[i] > secmax)//当第二大的数字在最大的数后边时,上边的方法就不行了,必须加这个
//如果nums[i]大于第二大的数 且小于最大数时 只更新第二大数就可以了
{
secmax = nums[i];
}
}
return secmax;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐