#include <stdio.h>
#include <stdlib.h>
typedef struct _SCORE
{
char ID[10];
int SS[2];
double Avg;
int Num;
} SCORE;
main()
{
int ret, i, j, k, count, who, highest;
SCORE *pScore;//int score[100];
FILE * stream;
//dynamic memory allocation 100 Scores
pScore = (SCORE *) calloc(100, sizeof(SCORE));
char filename[20]="score2.txt";
if( (stream = fopen( filename, "r" )) == NULL )
{
printf( "The file %s was not opened\n", filename );
return -1;
}
i=0; count=0;
ret = fscanf(stream, "%8c %d %d\n",
&pScore[i].ID,&pScore[i].SS[0], &pScore[i].SS[1]);
while (ret != EOF)
{
pScore[i].Avg = 0.5*(pScore[i].SS[0]+pScore[i].SS[1]);
pScore[i].Num = 0;
i = i+1;
ret = fscanf(stream, "%8c %d %d\n",
&pScore[i].ID,&pScore[i].SS[0], &pScore[i].SS[1]);
}
fclose(stream);
count = i;
/*算有幾個人比你分數高*/
for (j=0; j<count; j++)
{
k = 0;
for (i=0; i< count; i++)
{
if (pScore[i].Avg > pScore[k].Avg)
{
k++;
}
}
pScore[j]= k + 1;
}
for (i=0; i< count; i++)
{
pScore[i].Avg = 0.5*(pScore[i].SS[0]+pScore[i].SS[1]);
printf("%s %2d %2d %4.2f %2d\n",
pScore[i].ID, pScore[i].SS[0],pScore[i].SS[1], pScore[i].Avg, pScore[i].Num);
}
free(pScore);
return 0;
}
Tags: 98(上), C程式
#include <stdio.h>
#include <stdlib.h>
typedef struct _Score{
char ID[10];
int SS[3];
double Avg;
} SCORE;
int compare( const void *arg1, const void *arg2 );
main()
{
int ret, i, ss, sum, average, count;
SCORE *pScore;
FILE * stream;
char filename[20]="score3.txt";
pScore = (SCORE*) calloc(100, sizeof(SCORE));
if( (stream = fopen( filename, "r" )) == NULL )
{
printf( "The file %s was not opened\n", filename );
return -1;
}
i=0; count=0;
ret = fscanf(stream, "%8c %d %d %d\n", &pScore[i].ID, &pScore[i].SS[0], &pScore[i].SS[1], &pScore[i].SS[2]);
while (ret != EOF)
{
pScore[i].Avg = 0.33333333333*(pScore[i].SS[0]+pScore[i].SS[1]+pScore[i].SS[2]);
i++;
ret = fscanf(stream, "%8c %d %d %d\n", &pScore[i].ID, &pScore[i].SS[0], &pScore[i].SS[1], &pScore[i].SS[2]);
}
fclose(stream);
count = i;
qsort(pScore, count, sizeof(SCORE), compare);
for (i=0; i< count; i++)
{
printf("%2d %8s %2d %2d %2d %6.2f \n", i+1, pScore[i].ID, pScore[i].SS[0], pScore[i].SS[1], pScore[i].SS[2], pScore[i].Avg);
}
return 0;
}
int compare( const void *arg1, const void *arg2 )
{
double diff = (*((SCORE*)arg1)).Avg - (*((SCORE*)arg2)).Avg;
if (diff > 0)
return -1;
else
return 1;
return 0;
}
Tags: 98(上), C程式