Miki_Sa_yaka 2022-08-08 11:28 采纳率: 77.8%
浏览 30
已结题

C++ 结构体_指针_函数例题

问题遇到的现象和发生背景

不明白为什么我的随机数只赋值了一遍,不明白为什么我的teacher就打印了一遍

问题相关代码,请勿粘贴截图
#include <iostream>
#include <ctime>
#include <string>
using namespace std;

// 学生结构体
struct Student
{
    // 学生姓名
    string Name_stu;

    // 学生分数(随机数)
    int Score;
};

// t结构体
struct Teacher
{
    // t姓名
    string Name_tch;

    // 学生数组
    struct Student Array_stu[5];
};

// 函数声明

// 命名函数
void Allocate_name(struct Teacher Array_tch[], int len_tch, int len_stu);
// 传入t数组,t数组长度,学生数组长度

// 打印函数
void Print_result(struct Teacher Array_tch_fun[], int len_tch, int len_stu);
// 传入t数组,t数组长度,学生数组长度

int main()
{

    // 1.创建一个有三个t的数组

    struct Teacher Array_tch[3];

    // 2.给每个t名字,给每个学生赋值名字和分数(随机数)

    int len_tch = sizeof(Array_tch) / sizeof(Array_tch);
    int len_stu = sizeof(Array_tch->Array_stu) / sizeof(Array_tch->Array_stu[0]);
    Allocate_name(Array_tch, len_tch, len_stu);

    // 3.打印出结果

    Print_result(Array_tch, len_tch, len_stu);

    return 0;
}



// 命名和赋值函数
void Allocate_name(struct Teacher Array_tch[], int len_tch, int len_stu)
{
    string Nameseed = "ABCDE";
    
    // teacher 命名
    for (int i = 0; i < len_tch; i++)
    {
        Array_tch[i].Name_tch = "Teacher_";
        Array_tch[i].Name_tch += Nameseed[i];

        // student 命名
        for (int j = 0; j < len_stu; j++)
        {
            Array_tch[i].Array_stu[j].Name_stu = "Student_";
            Array_tch[i].Array_stu[j].Name_stu += Nameseed[j];

            // student 赋分
            srand((unsigned)time(NULL));
            int num = rand() % 101; // 0到100
            
            Array_tch[i].Array_stu[j].Score = num;
        }
    }
}


// 打印函数
void Print_result(struct Teacher Array_tch_fun[],int len_tch, int len_stu)
{
    // 打印t信息
    for (int i = 0; i < len_tch; i++)
    {
        cout << Array_tch_fun[i].Name_tch << "\t" << endl;

        // 打印学生姓名和分数
        for (int j = 0; j < len_stu; j++)
        {
            cout << Array_tch_fun[i].Array_stu[j].Name_stu << "\t"
                 << "得分:" << "\t" << Array_tch_fun[i].Array_stu[j].Score << "\t" << endl;
        }
        cout << endl;
    }
}

运行结果及报错内容

img

我的解答思路和尝试过的方法

解决不了

我想要达到的结果

ABC t各带ABCDE五个学生,

img

  • 写回答

3条回答 默认 最新

  • [PE]经典八炮 2022-08-08 12:02
    关注

    len_tch算错了,srand放到main里面只调用一次

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 8月16日
  • 已采纳回答 8月8日
  • 创建了问题 8月8日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改