C++学习笔记基础篇17——结构体数组和指针

小作业:

①、根据运算符的优先级,大家想一下:

Student stu[2] =
{
        { "aaa", 0, 'f', 10 },
        { "bbb", 0, 'm', 12 }
};

Student* pstu = stu;
++pstu->num = 202; 

//这句代码执行之后,到底是stu[0] 的 num 值变化了,还是 stu[1] 的 num 值变化了?

答:++的优先级低于->,所以等于先对stu[0]进行赋值,然后对pstu指针指向下一个数组。

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

#include <iostream>
using namespace std;
#include <string> //C++语法

struct Student
{
	string name;
	int num;
	float mark;
};

void set_num(Student* stu)
{
	static int stu_num = 101;
	(*stu).num = stu_num++;
}

int main(int argc, char* argv[])
{
	Student stu[5];
	for (int idx = 0; idx < 5; idx++)
	{
		cout << "请输入第"<<idx+1<<"个学生姓名" << endl;
		cin >> stu[idx].name;
		cout << "请输入第" << idx+1 << "个学生学号" << endl;
		cin >> stu[idx].num;
		cout << "请输入第" << idx+1 << "个学生成绩" << endl;
		cin >> stu[idx].mark;
	}
	Student* pstu = stu;
	
	//遍历
	int sum_mark;
	for (int idx = 0; idx < 5; ++idx)
	{
		cout << stu[idx].name << " " << stu[idx].num << " " << stu[idx].mark << endl;
		sum_mark = +stu[idx].mark;
	}
	cout << "平均成绩为" << sum_mark/5 << endl;
	system("pause");
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值