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

相关推荐
暖阳华笺34 分钟前
Leetcode刷题 由浅入深之哈希表——242. 有效的字母异位词
数据结构·c++·算法·leetcode·哈希表
敲上瘾1 小时前
线程池的封装(c/c++)
linux·服务器·c++·算法·缓存·池化技术
代码程序猿RIP1 小时前
C++(22)—内存管理
开发语言·数据结构·c++·算法
孞㐑¥1 小时前
C++之哈希
开发语言·c++·经验分享·笔记
奇树谦2 小时前
C/C++语言常见问题-智能指针、多态原理
c语言·开发语言·c++
溟洵2 小时前
【C++ Qt】Hello World、初始信号槽、理解对象树 ~~~(通俗易懂 图文并茂)
开发语言·c++·qt
haaaaaaarry3 小时前
【贪心】C++ 活动安排问题
开发语言·c++·算法·贪心
君义_noip3 小时前
信息学奥赛一本通 1508:Easy SSSP
c++·图论·信息学奥赛
末央&3 小时前
【C++】深入浅出之继承
开发语言·c++
可乐^奶茶4 小时前
2026《数据结构》考研复习笔记二(C++面向对象)
数据结构·c++·笔记