结构体数组与指针

5、小作业:
①、根据运算符的优先级,大家想一下:
Student stu[2] =
{
        { "aaa", 0, 'f', 10 },
        { "bbb", 0, 'm', 12 }
};

Student* pstu = stu;
++p->num = 202; //这句代码执行之后,到底是stu[0] 的 num 值变化了,还是 stu[1] 的 num 值变化了?

#include <iostream>
using namespace std;
struct Student
{
    string name;
    int num;
    char sex;
    short age;
};
int main()
{
    //①、根据运算符的优先级,大家想一下:
    Student stu[2] =
    {
            { "aaa", 0, 'f', 10 },
            { "bbb", 0, 'm', 12 }
    };
    Student* pstu = stu;
    ++pstu->num = 202; //这句代码执行之后,到底是stu[0] 的 num 值变化了,还是 stu[1] 的 num 值变化了?
    cout << stu->num << endl;
    cout << stu[1].num << endl;
    //->对象指针比++自加运算符优先级高
    return 0;
}

②、定义一个学生类型的结构体,包含学生的:姓名、学号、分数。之后用该结构体定义大小为5的结构体变量数组。手动输入给数组成员赋值,之后将5个学生的信息输出出来,并且求出5个学生的分数的平均值也一起输出出来。

#include <iostream>
#include <string>
using namespace std;
struct Student
{
    string name;
    int S_num;
    int score;
};
int Average(Student* stu)
{
    int temp = 0;
    for (int i = 0; i < 5; ++i)
    {
        temp += stu[i].score;
    }

    return temp / 5;
}
int main()
{
    //②、定义一个学生类型的结构体,包含学生的:姓名、学号、分数。
    //之后用该结构体定义大小为5的结构体变量数组。手动输入给数组成员赋值,
    //之后将5个学生的信息输出出来,并且求出5个学生的分数的平均值也一起输出出来。
    Student stu[5] = {
        {"a",0,10},
        {"b",1,15},
        {"c",2,5},
        {"d",3,60},
        {"e",4,100}
    };
    cout << "将5个学生的信息输出出来" << endl;
    for (int i = 0; i < 5; ++i)
    {
        cout << "姓名 = "<< stu[i].name << " " << "学好 = " << stu[i].S_num << " " << 
            "分数 = " << stu[i].score << endl;
    }

    int i_Average = Average(stu);
    cout << "平均值 = " <<i_Average << endl;
    return 0;
}

 

posted on 2021-01-03 20:26  SakuraQAQ  阅读(293)  评论(0)    收藏  举报

导航