编写下列函数:
void find_two_largest(const int*a,int n,int*largest,int*second_largest);
a指向长度为n的数组。函数从数组中找出最大和第二大元素,并把它们分别储存到由largest和second_largest指向的变量中,要求使用指针算术运算而不是取下标来访问数组元素。
//从数组中找出最大和第二大元素,并把它们分别储存到由largest和second_largest指向的变量中
#include<stdio.h>
int main()
{
void find_two_largest(const int *a, int n, int *largest, int *second_largest);
int i, *a, *L, *SL, arr[10];
for (i = 0;i < 10;i++)
{
scanf_s("%d", &arr[i]);
}
a = arr;
if (a[0]>a[1])
{
L = &a[0];
SL = &a[1];
}
else
{
L = &a[1];
SL = &a[0];
}
find_two_largest(a, 10, L, SL);
}
void find_two_largest(const int *a, int n, int *largest, int *second_largest)
{
int i, s;
for (i = 1;i <= n;i++, a++)
{
if (*largest < *a)
{
if(*second_largest < *largest)
*second_largest = *largest;
*largest = *a;
}
else if (*second_largest < *a)
{
s = *second_largest;
*second_largest = *a;
if (*second_largest == *largest)
*second_largest = s;
}
}
if (*second_largest > *largest) // 最后再次确认
{
s = *second_largest;
*second_largest = *largest;
*largest = s;
}
printf("largest = %d, second_largest = %d\n",*largest,*second_largest);
}