找出最低分数的同学,储存到h指向的结构体数组
#include<stdio.h>
#include<math.h>
#define N 10
#define eps 1e-4
struct stu
{
double num;
float score;
};
int main()
{
struct stu s[N],low[N],*Q=s,*h=low;
int i;float min=100.0;
for(i=0;i<N;i++)
{
scanf("%lf %f",&(Q+i)->num,&(Q+i)->score);
if(min>(Q+i)->score) min=(Q+i)->score;//输入的同时找最低分数
}
int fun(struct stu *,struct stu *,float);
int sum=fun(Q,h,min);
printf("分数最低的同学有%d个\n",sum);
for(i=0;i<sum;i++)
{
printf("%0.0lf\t%0.1f\n",(h+i)->num,(h+i)->score);
}return 0;
}
int fun(struct stu *Q,struct stu *h,float min)
{
int sum=0,i;
for(i=0;i<N;i++)
{
if(fabs(min-(Q+i)->score)<eps)//遍历s[N]若某元素分数最低,
{
sum++;
*(h++)=*(Q+i);//将数据放到h所指的数组中
}
}return sum;
}
/*202101 98.4
202102 97.1
202103 98.2
202104 97.1
202105 100
202106 97.1
202107 99.5
202108 100
202109 97.2
202110 97.1*/
以h[0]为例,h[0]是一个指针,在未执行h[0]=s+i前,h[0]的值为任意值,未指向任何变量,因此*h[0]并不能被赋值,如果代码里用了*h[j++]=*(s+i),与此类似。而h[j++]=s+i则是对指针h[j++]赋值了明确的地址,*h[j++]此时才变得有意义
#include<stdio.h>
#include<math.h>
#define N 10
#define eps 1e-4
typedef struct stu
{
long num;
float score;
}STU;int i;
int main()
{
STU s[N],*h[N];
int i;float min=100;
for(i=0;i<N;i++)
{
scanf("%ld %f",&s[i].num,&s[i].score);
if(min>(s+i)->score) min=(s+i)->score;
}
int fun(STU *h[],const STU s[],const float);
int num=fun(h,s,min);
printf("\n分数最低的学生有%d个:\n",num);
for(i=0;i<num;i++)
printf("%ld\t%.1f\n",h[i]->num,h[i]->score);
return 0;
}
int fun(STU *h[],const STU s[],const float min)
{
int num=0;
for(i=0;i<N;i++)
{
if(fabs(min-(s+i)->score)<eps) h[num++]=s+i;
}
return num;
}
/*202101 98.4
202102 97.1
202103 98.2
202104 97.1
202105 100
202106 97.1
202107 99.5
202108 100
202109 97.2
202110 97.1*/
效果