用c++面向程序设计建立一个对象数组,内放5(至少5个)个学生的数据(学号、成绩),统计出学生的个数,计算出平均成绩。
时间: 2024-06-01 11:13:02 浏览: 29
#include <stdio.h>
struct Student{
int id;
int score;
};
int main(){
struct Student students[5] = {{1001, 80},
{1002, 90},
{1003, 85},
{1004, 95},
{1005, 87}};
int count = sizeof(students) / sizeof(students[0]); // 计算学生个数
int sum = 0;
for(int i = 0; i < count; i++){
sum += students[i].score; // 计算总成绩
}
float average = (float)sum / count; // 计算平均成绩
printf("学生个数:%d\n", count);
printf("平均成绩:%.2f\n", average);
return 0;
}
相关问题
建立一个对象数组,内放5个学生的学号和成绩,用指针指向数组首元素输出全部学生的数据
可以使用以下代码建立对象数组并输出全部学生的数据:
```c++
#include <iostream>
using namespace std;
class Student {
public:
int id;
int score;
};
int main() {
Student students[5] = {{1, 90}, {2, 85}, {3, 92}, {4, 88}, {5, 95}};
Student* p = students;
for (int i = 0; i < 5; i++) {
cout << "学号:" << p->id << ",成绩:" << p->score << endl;
p++;
}
return 0;
}
```
输出结果为:
```
学号:1,成绩:90
学号:2,成绩:85
学号:3,成绩:92
学号:4,成绩:88
学号:5,成绩:95
```
在c++中,建立一个对象数组,内放5 (至少5个)个学生的数据(学号、成绩),统计出学生的个数,计算出平均成绩。
好的,这个问题很简单。您可以这样编写代码:
```c
#include <stdio.h>
struct Student {
int id;
float score;
};
int main() {
struct Student students[5] = {
{1001, 89.5},
{1002, 76.0},
{1003, 92.5},
{1004, 85.0},
{1005, 78.5}
};
int count = sizeof(students) / sizeof(students[0]);
float sum = 0.0;
for (int i = 0; i < count; i++) {
sum += students[i].score;
}
float average = sum / count;
printf("学生个数:%d\n", count);
printf("平均成绩:%.2f\n", average);
return 0;
}
```
这个程序定义了一个学生结构体,包含学号和成绩两个成员变量。然后创建了一个包含5个学生数据的对象数组,使用循环遍历数组来计算总成绩并统计学生个数,最后计算平均成绩并输出结果。
希望能够帮到您!