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

相关推荐
JCBP_5 分钟前
QT(4)
开发语言·汇编·c++·qt·算法
会开花的二叉树32 分钟前
继承与组合:C++面向对象的核心
java·开发语言·c++
潮汐退涨月冷风霜1 小时前
数字图像处理(1)OpenCV C++ & Opencv Python显示图像和视频
c++·python·opencv
第七序章3 小时前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
逆小舟4 小时前
【Linux】人事档案——用户及组管理
linux·c++
风中的微尘9 小时前
39.网络流入门
开发语言·网络·c++·算法
混分巨兽龙某某10 小时前
基于Qt Creator的Serial Port串口调试助手项目(代码开源)
c++·qt creator·串口助手·serial port
小冯记录编程10 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
C_Liu_11 小时前
C++:类和对象(下)
开发语言·c++
coderxiaohan11 小时前
【C++】类和对象1
java·开发语言·c++