#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]);来计算长度;

相关推荐
墨雪不会编程2 分钟前
C++之【深入理解Vector】三部曲最终章
开发语言·c++
cpp_25015 分钟前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷
kyle~11 分钟前
ROS2---QoS策略
c++·机器人·ros2
爱吃生蚝的于勒21 分钟前
【Linux】进程信号之捕捉(三)
linux·运维·服务器·c语言·数据结构·c++·学习
君生我老1 小时前
C++自写list类
c++
阿猿收手吧!1 小时前
【C++】异步编程:std::async终极指南
开发语言·c++
REDcker1 小时前
gRPC开发者快速入门
服务器·c++·后端·grpc
doupoa1 小时前
内存指针是什么?为什么指针还要有偏移量?
android·c++
冉佳驹2 小时前
C++ ——— 异常处理的核心机制和智能指针管理
c++·异常捕获·异常继承体与多态·重载抛异常·raii思想·智能指针shared_ptr·weak_ptr指针
C++ 老炮儿的技术栈2 小时前
Qt 编写 TcpClient 程序 详细步骤
c语言·开发语言·数据库·c++·qt·算法