#70结构体案例1(导师,学生,成绩)

效果:

代码:

cpp 复制代码
#include <iostream>
#include <string>
using namespace std;

#include "random"

int get_random_num(int min,int max)
{
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(min,max);
    int random_number = dis(gen);
    return random_number;
}

//结构体,学生(姓名,分数)
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;                //学生成绩  rand()%60是0-59随机数
            int random = get_random_num(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(){
    struct Teacher tArray[3];
    int len=sizeof(tArray)/sizeof (tArray[0]);
    allocateSpace(tArray,len);
    printInfo(tArray,len);
    return 0;
}

总结:

1)使用字符串要先声明#include <string>;

2)结构体结尾需要加分号,结构体可以包含结构体;

3)函数的定义如图,参数列表要写全,例:void allocateSpace(struct Teacher tArray[],int len);

4)随机数int num=random()%60是随机生成0-59的意思;

5)len表长度,可以用int len=sizeof(Array)/sizeof(Array[0]);来计算长度;

相关推荐
郭涤生5 小时前
布隆过滤器
c++
智者知已应修善业5 小时前
【求中位数】2024-1-23
c语言·c++·经验分享·笔记·算法
9ilk5 小时前
【C++】--- 特殊类设计
开发语言·c++·后端
程序员zgh9 小时前
Linux系统常用命令集合
linux·运维·服务器·c语言·开发语言·c++
獭.獭.9 小时前
C++ -- STL【unordered_set与unordered_map的实现】
开发语言·c++·unordered_map·unordered_set
qq_4335545410 小时前
C++数位DP
c++·算法·图论
似水এ᭄往昔10 小时前
【C++】--AVL树的认识和实现
开发语言·数据结构·c++·算法·stl
程序员zgh10 小时前
常用通信协议介绍(CAN、RS232、RS485、IIC、SPI、TCP/IP)
c语言·网络·c++
暗然而日章10 小时前
C++基础:Stanford CS106L学习笔记 8 继承
c++·笔记·学习
有点。11 小时前
C++ ⼀级 2023 年06 ⽉
开发语言·c++