习题一:三名老师,每人带五名学生,打印相关信息,学生成绩随机分配。
#include<iostream>
using namespace std;
#include<string>
#include<ctime>
struct Student {
string sName;
int score;
};
struct Teacher {
string tName;
struct Student sArray[5];
};
void allocateSpace(struct Teacher tArray[],int len) {
string nameSeed="ABCDE";
for (int i = 0; i < len; i++) {
tArray[i].tName = "Teacher_";
tArray[i].tName += nameSeed[i];
for (int j = 0; j < 5; j++) {
tArray[i].sArray[j].sName = "Student_";
tArray[i].sArray[j].sName +=nameSeed[j];
int random = rand() % 61+40;//0~60分->40~100分
tArray[i].sArray[j].score = random;
}
}
}
void printInfo(struct Teacher tArray[], int len) {
for (int i = 0; i < len; i++) {
cout << "老师的姓名:" << tArray[i].tName << endl;
for (int j = 0; j < 5; j++) {
cout << "\t学生姓名:" << tArray[i].sArray[j].sName <<
"考试分数:" << tArray[i].sArray[j].score << endl;
}
}
}
int main() {
//随机数种子,按照系统时间
srand((unsigned int)time(NULL));
//创建三名老师的数组
struct Teacher tArray[3];
int len = sizeof(tArray) / sizeof(tArray[0]);
allocateSpace(tArray, len);
printInfo(tArray, len);
return 0;
}
习题二:五个英雄,按年龄冒泡排序
#include<iostream>
using namespace std;
#include<string>
#include<ctime>
//1设计英雄结构体
struct Hero
{
string name;
int age;
string sex;
};
void bubbleSort(struct Hero heroArray[], int len)
{
for (int i = 0; i < len - 1; i++)
{
for (int j = 0; j < len - 1 - i; j++)
{
//如果j大于,交换
if (heroArray[j].age > heroArray[j + 1].age)
{
struct Hero temp = heroArray[j];
heroArray[j] = heroArray[j + 1];
heroArray[j + 1] = temp;
}
}
}
}
void printHero(struct Hero heroArray[], int len)
{
for (int i = 0; i < len; i++)
{
cout << "姓名:" << heroArray[i].name << " 年龄:" << heroArray[i].age << " 性别:" << heroArray[i].sex << endl;
}
}
int main() {
//2创建数组
struct Hero heroArray[5] =
{
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"}
};
int len = sizeof(heroArray) / sizeof(heroArray[0]);
/*for (int i = 0; i < len; i++)
{
cout << "姓名:" << heroArray[i].name << " 年龄:" << heroArray[i].age << " 性别:" << heroArray[i].sex << endl;
}*/
//3对数组进行排序,将排序后的结果打印输出
bubbleSort(heroArray,len);
printHero(heroArray,len);
system("pause");
return 0;
}