问题遇到的现象和发生背景
多次调用成绩排序函数,之后几次无法实现;文件无法正常读写
问题相关代码,请勿粘贴截图
/数学排名
fun(score1,NUM);
while(j<NUM)
{
for(i=0; i<NUM; i++)
if(stu[i].math==score1[j])
{
stu[i].rank_math=j+1;
}
j++;
}
//计算机排名
fun(score2,NUM);
while(k<NUM)
{
for(i=0; i<NUM; i++)
if(stu[i].computer==score2[k])
{
stu[i].rank_computer=k+1;
}
k++;
}
//英语排名
fun(score3,NUM);
while(l<NUM)
{
for(i=0; i<NUM; i++)
if(stu[i].English==score3[l])
{
stu[i].rank_English=l+1;
}
l++;
}
//总成绩排名
fun(score,NUM);
while(m<NUM)
{
for(i=0; i<NUM; i++)
if(stu[i].sum==score[m])
{
stu[i].rank=m+1;
}
m++;
}
我的解答思路和尝试过的方法
我想要达到的结果:成绩排名,文件存储
以下为错误程序:
#include <stdio.h>
#include<string.h>
#include<math.h>
#define NUM 3
struct student_score
{
char ID[10];
float math;
int rank_math;
float computer;
int rank_computer;
float English;
int rank_English;
float sum;
int rank;
char name[10];
char code[10];
}stu[NUM];
void fun(float p,int n)/排序并删除数组中重复元素/
{
int i,j,k,temp;
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if((p+i)<(p+j))
{
temp=(p+j);
(p+j)=(p+i);
(p+i)=temp;
}}}
for(i=0;i<n;i++) //循环判断数组中每一个数
{
for(j=i+1;j<n;j++) //判断a[i]后边的数是否和a[i]相等
{
if((p+i)==*(p+j))
{
for(temp=j;temp<n;temp++)
(p+temp)=(p+temp+1); //将a[j]后面的元素全往前移一个位置
j--; //a[j+1]取代a[j]位置,为使下次从a[j+1]开始查找,j减一(为使j保持不变)
n--; //数组长度减一
}}}
}
int main()
{
int i,j=0,k=0,l=0,m=0;
float temp;
float score1[NUM],score2[NUM],score3[NUM],score[NUM];
for(i=0;i<NUM;i++)
scanf("%s%f%f%f%s",stu[i].ID,&stu[i].math,&stu[i].computer,
&stu[i].English,stu[i].name);/输入各科成绩/
for(i=0;i<NUM;i++)
stu[i].sum=stu[i].math+stu[i].computer+stu[i].English;/总分/
for(i=0;i<NUM;i++)
{
score[i]=stu[i].sum;
score1[i]=stu[i].math;
score2[i]=stu[i].computer;
score3[i]=stu[i].English;}
//数学排名
fun(score1,NUM);
while(j<NUM)
{
for(i=0; i<NUM; i++)
if(stu[i].math==score1[j])
{
stu[i].rank_math=j+1;
}
j++;
}
//计算机排名
fun(score2,NUM);
while(k<NUM)
{
for(i=0; i<NUM; i++)
if(stu[i].computer==score2[k])
{
stu[i].rank_computer=k+1;
}
k++;
}
//英语排名
fun(score3,NUM);
while(l<NUM)
{
for(i=0; i<NUM; i++)
if(stu[i].English==score3[l])
{
stu[i].rank_English=l+1;
}
l++;
}
//总成绩排名
fun(score,NUM);
while(m<NUM)
{
for(i=0; i<NUM; i++)
if(stu[i].sum==score[m])
{
stu[i].rank=m+1;
}
m++;
}
for(i=0;i<NUM;i++)
printf("%s %.1f %d %.1f %d %.1f %d %.1f %d\n",
stu[i].ID,
stu[i].math,stu[i].rank_math,
stu[i].computer,stu[i].rank_computer,
stu[i].English,stu[i].English,
stu[i].sum,stu[i].rank);
/存入文件/
FILE *fp;
if((fp=fopen("F:\stu_list,txt","w"))==NULL)
{ printf("cannot open file\n");
return 1; }
for(i=0;i<NUM;i++)
fprintf(fp,"%s %f %d %f %d %f %d %f %d %s\n",stu[i].ID,
stu[i].math,stu[i].rank_math,
stu[i].computer,stu[i].rank_computer,
stu[i].English,stu[i].English,
stu[i].sum,stu[i].rank,
stu[i].name[10]);
fclose(fp);
}