#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 20
#define MAX 30
/*baseball.txt
4 Jessie Joybat 5 2 1 1
4 Jessie Joybat 7 3 5 3
7 Jack Donner 6 3 1 2
11 Martin Garder 4 3 2 1
15 Jaime Curtis 7 4 1 2
2 Curtis Michel 3 2 2 3
9 Gillan Morthim 9 6 6 7
12 Brett Tyler 8 7 4 3
8 Hans Gunner 7 7 2 3
14 Jessie James 11 2 3 4
12 Brett Tyler 4 3 1 3
0 xukun cai 100 1 1 1
*/
struct data
{
int num;
char fname[LEN];
char lname[LEN];
int stages;
int hit;
int go;
int rbi;
float andalv;//安打率
}player[LEN],player_count[LEN];
void bubble_sort(int arr[], int len) ;
int remove_duplicates(int arr[], int len);
int main(void)
{
int nums[LEN];
int len,i=0,j;
char str[LEN][MAX];
FILE *fp;
fp = fopen("baseball.txt", "r");
while(fscanf(fp,"%d %s %s %d %d %d %d\n", &player[i].num, player[i].fname,
player[i].lname,&player[i].stages,&player[i].hit,&player[i].go,&player[i].rbi)!=EOF)
{
printf("%d %s %s %d %d %d %d\n",player[i].num, player[i].fname,player[i].lname,
player[i].stages,player[i].hit,player[i].go,player[i].rbi);
i++;
}
for(i=0;i<LEN;i++)
{
nums[i]=player[i].num;
}
len = remove_duplicates(nums, LEN);//数组去重后得到新的长度
bubble_sort(nums, len) ;
for(i=0;i<len;i++)
{
printf("球员引索:%d\n",nums[i]);
}
for(i=0;i<len;i++)
{
for(j=0;j<LEN;j++)
{
if(nums[i]==player[j].num&&player[j].fname[0]!='\0')//不判断'\0' 会导致0号球员没有名字
{
player_count[i].num = player[j].num;
player_count[i].stages+= player[j].stages;
strcpy(player_count[i].fname, player[j].fname);
strcpy(player_count[i].lname, player[j].lname);
player_count[i].hit+= player[j].hit;
player_count[i].go+= player[j].go;
player_count[i].rbi+= player[j].rbi;
}
}
player_count[i].andalv = (float)(player_count[i].hit)/(player_count[i].stages);//每个i算一次安打率
}
printf("统计后\n" );
for(i=0;i<len;i++)
{
printf("球员号:%d %s %s 场次:%d 击中数:%d 走垒数:%d RBI:%d 安打率:%f\n",player_count[i].num,
player_count[i].fname,player_count[i].lname,player_count[i].stages,player_count[i].hit,
player_count[i].go,player_count[i].rbi,player_count[i].andalv);
}
fclose(fp);
return 0;
}
void bubble_sort(int arr[], int len)
{
int i, j, temp;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - 1 - i; j++)
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
int remove_duplicates(int arr[], int len)
{
int i,j,temp;
for(i=0;i<len;i++) //循环判断数组中每一个数
{
for(j=i+1;j<len;j++) //判断a[i]后边的数是否和a[i]相等
{
if(arr[i]==arr[j])
{
for(temp = j;temp<len-1;temp++)
arr[temp]=arr[temp+1]; //将a[j]后面的元素全往前移一个位置
j--; //a[j+1]取代a[j]位置,为使下次从a[j+1]开始查找,j减一(为使j保持不变)
len--; //数组长度减一
}
}
}
return len;
}