//用结构体数组存放5个人的信息(姓名、性别、年龄),统计5个人中男女人数并输出,并输出年龄最小和最大者的姓名
#include<iostream>
using namespace std;
struct Person
{
char name[20];
char sex;
int age;
};
int main()
{
Person stu[5];
int i,a=0,b=0;
for(i=0;i<5;i++)
{
cout<<"please enter the information:"<<endl;
cin>>stu[i].name>>stu[i].sex>>stu[i].age;
if(stu[i].sex=='F')
a++;
else
b++;
}
cout<<" there are "<<a<<"girls"<<endl;
cout<<" there are "<<b<<"boys"<<endl;
int j,k=1,h=1;
for(j=2;j<6;j++)
{
if(stu[k].age<stu[j].age)
k=j;
if(stu[h].age>stu[j].age)
h=j;
}
cout<<"the oldest person is "<<stu[k].name<<endl;
cout<<"the youngest person is "<<stu[h].name<<endl;
return 0;
}
/*#include<iostream>
using namespace std;
struct Student
{ char name[20];
char sex;
int age;
};
int main()
{
Student stu[5]={{"Wang",'M',20},{"Liu",'F',16},{"Li",'M',24},{"Yuan",'M',19},{"Zhang",'F',17}};
int i,min,max;
int n1=0,n2=0;
char M,F;
for(i=0;i<5;i++)
{if('M'==stu[i].sex)
n1++;
if('F'==stu[i].sex)
n2++;
}
cout<<"男生人数为:"<<n1<<endl;
cout<<"女生人数为:"<<n2<<endl;
min=0;
for(i=0;i<5;i++)
{
if(stu[min].age>stu[i].age)
min=i;
}
cout<<"年龄最小的同学为:"<<stu[min].name<<" "<<stu[min].age<<endl;
max=0;
for(i=0;i<5;i++)
{
if(stu[max].age<stu[i].age)
max=i;
}
cout<<"年龄最大的同学为:"<<stu[max].name<<" "<<stu[max].age<<endl;
return 0;
}
*/
该代码示例展示了如何用C++定义一个结构体`Person`来存储学生姓名、性别和年龄信息。通过输入5名学生的数据,程序会统计男生和女生的人数,并找出年龄最大和最小的学生姓名。
9261

被折叠的 条评论
为什么被折叠?



