这个,之前用的b去存储a的总和和排名,后来在比较的过程中,只改变的b的值,却没有改变a的值,但在比较语文成绩的时候用的还是a,这个时候a和b同样是第i个对应的可能不是同一个对象了
,因为上面b的值可能改变了,现在的第i个b可能是原来第i+1,i-1个,都有可能,所以比较结果错误。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n = 0;
scanf("%d", &n);
int(*a)[3] = (int*)malloc(sizeof(int) * 3 * n);
int i = 0;
int(*b)[2] = (int*)malloc(sizeof(int) * 2*n);
for (i = 0; i < n; i++)
{
scanf("%d %d %d", &a[i][0], &a[i][1], &a[i][2]);
b[i][0] = a[i][0] + a[i][1] + a[i][2];
b[i][1] = i+1;
}
for (i = 0; i < n; i++)
{
int max = 0;
int c = 0;
for (int j = 0; j < n - 1 - i; j++)
{
if (b[j][0] < b[j + 1][0])
{
max = b[j + 1][0];
b[j + 1][0] = b[j][0];
b[j][0] = max;
c = b[j + 1][1];
b[j + 1][1] = b[j][1];
b[j][1] = c;
}
else if(b[j][0] == b[j + 1][0])
{
if (a[j][0] < a[j + 1][0])
{
c = b[j + 1][1];
b[j + 1][1] = b[j][1];
b[j][1] = c;
}
else if(a[j][0] == a[j + 1][0])
if (b[j + 1][1] < b[j][1])
{
c = b[j + 1][1];
b[j + 1][1] = b[j][1];
b[j][1] = c;
}
}
}
}
for (i = 0; i < 5; i++)
{
printf("%d %d\n", b[i][1], b[i][0]);
}
free(a);
a = NULL;
free(b);
b = NULL;
return 0;
}
这个是正确的,不过感觉这样还是很麻烦
#include<stdio.h>
#include<stdlib.h>
struct Stu
{
int g[3];
int sum;
int n;
};
int main()
{
int n = 0;
scanf("%d", &n);
struct Stu* a = (struct Stu*)malloc(sizeof(struct Stu) * n);
struct Stu r;
int i = 0;
for (i = 0; i < n; i++)
{
scanf("%d %d %d", &a[i].g[0], &a[i].g[1], &a[i].g[2]);
a[i].sum = a[i].g[0] + a[i].g[1] + a[i].g[2];
a[i].n=i+1;
}
for (i = 0; i < n; i++)
{
int max = 0;
int c = 0;
for (int j = 0; j < n - 1 - i; j++)
{
if (a[j].sum < a[j+1].sum)
{
r = a[j];
a[j] = a[j + 1];
a[j + 1] = r;
}
else if(a[j].sum == a[j + 1].sum)
{
if (a[j].g[0] < a[j + 1].g[0])
{
r = a[j];
a[j] = a[j + 1];
a[j + 1] = r;
}
else if(a[j].g[0] == a[j + 1].g[0])
if (a[j].n>a[j+1].n)
{
r = a[j];
a[j] = a[j + 1];
a[j + 1] = r;
}
}
}
}
for (i = 0; i < 5; i++)
{
printf("%d %d\n", a[i].n,a[i].sum);
}
free(a);
a = NULL;
return 0;
}