直接上程序:
//ddim.c
#include
/*
*This program is used to read some data from the data file
*and then to process.
*/
int main(void)
{
int scores[5][3];//score array
float average;
float v[3];
int sum = 0;
int i,j;
FILE *fp;
if((fp = fopen("data.txt","r")) == NULL)
{
printf("Can't open the file!");
return -1;
}
for(i=0;i<3;i++)
{
for(j=0;j<5;j++)
{
fscanf(fp,"%d",&scores[j][i]);
sum += scores[j][i];
}
v[i] = sum/5;
sum = 0;
}
average = (v[0]+v[1]+v[2])/3;
if((fp = fopen("res.txt","w")) == NULL)
{
printf("Can't write to the file");
return -1;
}
fprintf(fp,"%s%.2f\n%s%.2f\n%s%.2f\n","Math:",v[0],"C:",v[1],"Java:",v[2]);
fprintf(fp,"%s%.2f","Total average:",average);
}
//data.txt
80 61 59 85 76
75 65 63 87 77
92 71 70 90 85
#gcc ddim.c -o ddim
#./ddim
得到结果:
//res.txt
Math:72.00
C:73.00
Java:81.00
Total average:75.33
注意:程序中不要出现for(int i=0;i