mesteron98#include <stdio.h> #include <stdlib.h> int compare(void *a, void *b) { int va = *(int*)a; int vb = *(int*)b; if(va == vb) return 0; return va < vb ? -1 : 1; }
int max_index(void *base, int n, int width, int (*compare)(void *a, void *b)) { int i, j = 0; char max[width]; memcpy(max, base, width); for(i = 1; i < n; i++) { if( compare(base+i*width, max) > 0) { memcpy(max, base+i*width, width); j = i; } } return j; }
int main() { int n; scanf("%d", &n); int a[n]; for(int i = 0; i < n; i++) scanf("%d", &a[i]); printf("%d\n", a[max_index(a, n, sizeof(int), compare)]); }
Answers & Comments
Verified answer
#include <stdio.h>int n=10;
int max(int x[n]) {
int m = x[0];
for (int i=1; i<n; i++) {
if (x[i]>m) m = x[i];
}
return m;
}
int main()
{
int a[n];
srand (time(NULL));
for (int i=0; i<n; i++)
{
a[i] = rand() % 1000;
printf ("%5d", a[i]);
}
printf("\n");
printf("max = %d", max(a));
return 0;
}
Пример:
486 338 716 381 344 143 255 109 490 527
max = 716
#include <stdlib.h>
int compare(void *a, void *b) {
int va = *(int*)a;
int vb = *(int*)b;
if(va == vb) return 0;
return va < vb ? -1 : 1;
}
int max_index(void *base, int n, int width, int (*compare)(void *a, void *b)) {
int i, j = 0;
char max[width];
memcpy(max, base, width);
for(i = 1; i < n; i++) {
if( compare(base+i*width, max) > 0)
{
memcpy(max, base+i*width, width);
j = i;
}
}
return j;
}
int main() {
int n;
scanf("%d", &n);
int a[n];
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("%d\n", a[max_index(a, n, sizeof(int), compare)]);
}