利用结构体类型编写程序,实现输入一个学生的数据(如学号、姓名、性别、3门课程的成绩),计算并输出其平均成绩。
时间: 2024-02-02 14:05:15 浏览: 20
好的,以下是实现该功能的 C++ 代码:
```c++
#include <iostream>
#include <string>
using namespace std;
// 定义学生结构体类型
struct Student {
string id; // 学号
string name; // 姓名
char gender; // 性别
double score1; // 第一门课程成绩
double score2; // 第二门课程成绩
double score3; // 第三门课程成绩
};
int main() {
Student stu; // 定义一个学生对象
double avg; // 平均成绩
// 输入学生数据
cout << "请输入学生的学号、姓名、性别和3门课程的成绩(用空格分隔):" << endl;
cin >> stu.id >> stu.name >> stu.gender >> stu.score1 >> stu.score2 >> stu.score3;
// 计算平均成绩
avg = (stu.score1 + stu.score2 + stu.score3) / 3.0;
// 输出学生数据和平均成绩
cout << "学生信息如下:" << endl;
cout << "学号:" << stu.id << endl;
cout << "姓名:" << stu.name << endl;
cout << "性别:" << stu.gender << endl;
cout << "第一门课程成绩:" << stu.score1 << endl;
cout << "第二门课程成绩:" << stu.score2 << endl;
cout << "第三门课程成绩:" << stu.score3 << endl;
cout << "平均成绩:" << avg << endl;
return 0;
}
```
运行程序后,会提示输入学生数据,输入完毕后即可计算并输出平均成绩和学生信息。