一道C语言题目。用结构体。运行环境VC
发布网友
发布时间:2022-04-19 09:54
我来回答
共1个回答
热心网友
时间:2023-06-23 17:10
#include<iostream>
#include <time.h>
#include <iomanip>
using namespace std;
#define NUM 30
#define NUM_START 20000
char names[NUM][20]={
"abc0","abc1","abc2","abc3",
"abc4","abc5","abc6","abc7",
"abc8","abc9","abc10","abc11",
"abc12","abc13","abc14","abc15",
"abc16","abc17","abc18","abc19",
"abc20","abc21","abc22","abc23",
"abc24","abc25","abc26","abc27",
"abc28","abc29"
};
struct Student
{
int Number;
char Name[20];
float scoChn;
float scoMath;
float scoEng;
};
Student stu[NUM];
void Init(Student*pst)
{
srand(time(NULL));
for(int i=0;i<NUM;i++)
{
pst[i].Number=NUM_START+i;
strcpy(pst[i].Name,names[i]);
pst[i].scoChn=51+rand()%50;
pst[i].scoMath=51+rand()%50;
pst[i].scoEng=51+rand()%50;
}
}
void Show(Student*pst)
{
cout<<setw(8)<<"学号"
<<setw(20)<<"姓名"
<<setw(10)<<"语文成绩"
<<setw(10)<<"数学成绩"
<<setw(10)<<"英语成绩"
<<setw(10)<<"总成绩"
<<endl;
for(int i=0;i<NUM;i++)
{
cout<<setw(8)<<pst[i].Number
<<setw(20)<<pst[i].Name
<<setw(10)<<pst[i].scoChn
<<setw(10)<<pst[i].scoMath
<<setw(10)<<pst[i].scoEng
<<setw(10)<<pst[i].scoEng+pst[i].scoChn+pst[i].scoMath
<<endl;
}
}
void ShowAtIndex(Student*pst,int i)
{
if(i==-1)
{
cout<<"查无此人!"<<endl;
return;
}
cout<<setw(8)<<"学号"
<<setw(20)<<"姓名"
<<setw(10)<<"语文成绩"
<<setw(10)<<"数学成绩"
<<setw(10)<<"英语成绩"
<<setw(10)<<"总成绩"
<<endl;
cout<<setw(8)<<pst[i].Number
<<setw(20)<<pst[i].Name
<<setw(10)<<pst[i].scoChn
<<setw(10)<<pst[i].scoMath
<<setw(10)<<pst[i].scoEng
<<setw(10)<<pst[i].scoEng+pst[i].scoChn+pst[i].scoMath
<<endl;
}
void Sort(Student*pst)
{
Student tmp;
int imax;
float max;
for(int i=0;i<NUM-1;i++)
{
max=pst[i].scoChn+pst[i].scoMath+pst[i].scoEng;
imax=i;
for(int j=i+1;j<NUM;j++)
{
if(max<pst[j].scoChn+pst[j].scoMath+pst[j].scoEng)
{
max=pst[j].scoChn+pst[j].scoMath+pst[j].scoEng;
imax=j;
}
}
if(imax!=i)
{
tmp.Number=pst[i].Number;
strcpy(tmp.Name,pst[i].Name);
tmp.scoChn=pst[i].scoChn;
tmp.scoMath=pst[i].scoMath;
tmp.scoEng=pst[i].scoEng;
pst[i].Number=pst[imax].Number;
strcpy(pst[i].Name,pst[imax].Name);
pst[i].scoChn=pst[imax].scoChn;
pst[i].scoMath=pst[imax].scoMath;
pst[i].scoEng=pst[imax].scoEng;
pst[imax].Number=tmp.Number;
strcpy(pst[imax].Name,tmp.Name);
pst[imax].scoChn=tmp.scoChn;
pst[imax].scoMath=tmp.scoMath;
pst[imax].scoEng=tmp.scoEng;
}
}
}
int FindByName(Student*pst,char*na)
{
for(int i=0;i<NUM;i++)
{
if(strcmp(pst[i].Name,na)==0)
return i;
}
return -1;
}
void main()
{
char name[20];
Init(stu);
Sort(stu);
Show(stu);
cout<<endl<<"请输入要查找的学生的名字:";
cin>>name;
int index=FindByName(stu,name);
cout<<"查询结果:"<<endl;
ShowAtIndex(stu,index);
}