# include <stdio.h>
# include <stdlib.h>
# define MAX_NAME_LEN 80
typedef struct scores scores;
struct scores {
int id;
char name[MAX_NAME_LEN];
int calc;
int com_prog;
int total;
int rank;
};
int input_scores(struct scores *, int);
int calc_scores(struct scores *, int);
int dump_scores(struct scores *, int);
void dump_score(struct scores *, int);
int main()
{
int total, i;
scores *scores;
puts("總共有幾個人?");
if (scanf("%d", &total) < 1)
exit(1);
else if ((scores = (struct scores *)malloc(sizeof (struct scores) * total)) == NULL)
exit(1);
putchar('\n');
input_scores(scores, total);
calc_scores(scores, total);
dump_scores(scores, total);
putchar('\n');
do {
printf("查詢 ID? (1 <= X <= %d; X == -1 結束)\n", total);
scanf("%d", &i);
i--;
if (i >= 0 && i < total)
dump_score(scores, i);
} while (i >= 0);
return 0;
}
int input_scores(struct scores *scores, int total)
{
int i;
for (i = 0; i < total; i++) {
scores[i].id = i + 1;
printf("ID: %d\n", i + 1);
puts("Name?");
scanf("%s", scores[i].name);
puts("Score of Calculus/Computer Program?");
scanf("%d%d", &scores[i].calc, &scores[i].com_prog);
putchar('\n');
}
return i;
}
int cmp_scores(const void *score1, const void *score2)
{
return (*(const struct scores **)score1)->total < (*(const struct scores **)score2)->total;
}
int calc_scores(struct scores *scores, int total)
{
int i;
struct scores **tmp;
if ((tmp = (struct scores **)malloc(sizeof (struct scores *) * total)) == NULL)
exit(1);
for (i = 0; i < total; i++) {
scores[i].total = scores[i].calc + scores[i].com_prog;
tmp[i] = &scores[i];
}
qsort(tmp, total, sizeof (scores), cmp_scores);
for (i = 0; i < total; i++)
tmp[i]->rank = i + 1;
free(tmp);
return i;
}
void dump_score(struct scores *scores, int i)
{
printf("[%d] %s\t%d\t%d\t%d\t%d\n",
scores[i].id, scores[i].name,
scores[i].calc, scores[i].com_prog,
scores[i].total, scores[i].rank);
}
int dump_scores(struct scores *scores, int total)
{
int i;
for (i = 0; i < total; i++)
dump_score(scores, i);
return i;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.182.27