C++ 结构体+数组+取随机数 案例(打印3名老师 带着 5名学生)结构体
作者:互联网
1 //结构体案列 2 3 #include<iostream> 4 #include<string> 5 #include<ctime> 6 using namespace std; 7 8 //学生的结构体 9 struct Student 10 { 11 string sName; 12 int score; 13 }; 14 15 //老师的结构体 16 struct Teacher 17 { 18 string tName; 19 struct Student sArray[5]; 20 21 }; 22 //给老师和学生赋值 23 void allocateSpace(struct Teacher tArray[],int len) 24 { 25 string nameSeed = "ABCDE"; 26 for (int i = 0; i < len; i++) 27 { 28 29 tArray[i].tName = "Teacher_"; 30 tArray[i].tName += nameSeed[i]; 31 for (int j = 0; j < 5; j++) 32 { 33 tArray[i].sArray[j].sName = "Student_"; 34 tArray[i].sArray[j].sName += nameSeed[j]; 35 36 int random = rand() % 60 + 40; 37 tArray[i].sArray[j].score = random; 38 39 40 } 41 42 43 } 44 } 45 46 //打印信息 47 void printfInfo(struct Teacher tArray[], int len) 48 { 49 for (int i = 0; i < len; i++) 50 { 51 cout << "老师的姓名: " << tArray[i].tName << endl; 52 53 for (int j = 0; j < 5; j++) 54 { 55 56 cout << "\t学生的姓名: " << tArray[i].sArray[j].sName <<" 考试分数: "<<tArray[i].sArray[j].score<< endl; 57 } 58 } 59 } 60 61 62 63 int main() 64 { 65 //随机数种子 66 srand((unsigned int )time(NULL)); 67 68 //创建3名老师的数组 69 struct Teacher tArray[3]; 70 71 //赋值 72 int len = sizeof(tArray) / sizeof(tArray[0]); 73 allocateSpace(tArray, len); 74 //打印 75 76 printfInfo(tArray, len); 77 78 }
标签:sArray,struct,int,C++,Teacher,len,随机数,tArray,结构 来源: https://www.cnblogs.com/Bytezero/p/15097530.html