建立一个对象数组,内放五个学生的数据(学号、成绩),用指针指向数组首元素,输出第1,3,5学生的数据
时间: 2023-05-19 20:04:54 浏览: 54
可以使用以下代码来建立一个对象数组,内放五个学生的数据(学号、成绩),并用指针指向数组首元素:
```
#include <iostream>
using namespace std;
class Student {
public:
int id;
int score;
};
int main() {
Student students[5] = {{1, 90}, {2, 80}, {3, 70}, {4, 60}, {5, 50}};
Student* ptr = &students[0];
cout << "第1个学生的数据:学号=" << ptr->id << ",成绩=" << ptr->score << endl;
ptr += 2;
cout << "第3个学生的数据:学号=" << ptr->id << ",成绩=" << ptr->score << endl;
ptr += 2;
cout << "第5个学生的数据:学号=" << ptr->id << ",成绩=" << ptr->score << endl;
return 0;
}
```
输出结果为:
```
第1个学生的数据:学号=1,成绩=90
第3个学生的数据:学号=3,成绩=70
第5个学生的数据:学号=5,成绩=50
```
相关问题
用c++编写 建立一个对象数组,内放五个学生的数据(学号、成绩),用指针指向数组首元素,输出第1,3,5学生的数据
以下是用 C++ 编写建立一个对象数组,内放五个学生的数据(学号、成绩),用指针指向数组首元素,输出第1,3,5学生的数据的代码:
```c++
#include <iostream>
using namespace std;
class Student {
public:
int id;
int score;
};
int main() {
Student students[5] = {{1, 90}, {2, 80}, {3, 70}, {4, 60}, {5, 50}};
Student* ptr = students;
cout << "第1个学生的学号和成绩:" << ptr->id << " " << ptr->score << endl;
ptr += 2;
cout << "第3个学生的学号和成绩:" << ptr->id << " " << ptr->score << endl;
ptr += 2;
cout << "第5个学生的学号和成绩:" << ptr->id << " " << ptr->score << endl;
return 0;
}
```
输出结果为:
```
第1个学生的学号和成绩:1 90
第3个学生的学号和成绩:3 70
第5个学生的学号和成绩:5 50
```
建立一个对象数组,内放5个学生的学号和成绩,用指针指向数组的首元素,输出第1,3,5学生的数据。用C++实现
下面是用C++实现的代码:
```cpp
#include <iostream>
using namespace std;
struct Student {
int id; // 学号
int score; // 成绩
};
int main() {
Student students[5] = {
{1001, 85},
{1002, 92},
{1003, 78},
{1004, 90},
{1005, 88}
}; // 定义并初始化学生数组
Student* p = students; // 使用指针指向数组的首元素
cout << "第1个学生的数据:" << endl;
cout << "学号:" << p->id << ",成绩:" << p->score << endl;
p += 2; // 指向第3个学生的数据
cout << "第3个学生的数据:" << endl;
cout << "学号:" << p->id << ",成绩:" << p->score << endl;
p += 2; // 指向第5个学生的数据
cout << "第5个学生的数据:" << endl;
cout << "学号:" << p->id << ",成绩:" << p->score << endl;
return 0;
}
```
输出结果:
```
第1个学生的数据:
学号:1001,成绩:85
第3个学生的数据:
学号:1003,成绩:78
第5个学生的数据:
学号:1005,成绩:88
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)