码迷,mamicode.com
首页 > 编程语言 > 详细

求数组的最大值和次大值

时间:2016-01-07 08:52:18      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <stdlib.h>

/*
	求数组的最大值和次大值。
*/
int main() {
	int n;
	while (printf("Please input n:\n"),fflush(stdin), scanf("%d", &n) != EOF){
		if (n < 2){
			printf("Please input a bigger number.\n");
			continue;
		}
		printf("Please input %d numbers:\n",&n);
		int *numbers = (int*)malloc(n*sizeof(int));
		for (int i = 0; i < n; ++i)
			scanf("%d",numbers+i);
		int max1, max2;
		if (numbers[0] > numbers[1]){
			max1 = numbers[0];
			max2 = numbers[1];
		}
		else{
			max1 = numbers[1];
			max2 = numbers[0];
		}
		for (int i = 2; i < n; ++i)
			if (numbers[i] > max1){
				max2 = max1;
				max1 = numbers[i];
			}
			else if (numbers[i] > max2)
				max2 = numbers[i];
		printf("The biggest number is: %d\n", max1);
		printf("The second biggest number is: %d\n", max2);
	}
	system("pause");
	return 0;
}

  

求数组的最大值和次大值

标签:

原文地址:http://www.cnblogs.com/mutaohengheng/p/5108041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!