Huake object-oriented programming assignment 2: write a program, input N student data, including student number, name, grade, and request to output these student data and calculate the average score

topic description

Write a program to input N student data, including student number, name, grade, and request to output
these student data and calculate the average score. Requirements:
➢Design the student class CStud, in addition to no (student number), name (name) and
score (grade) data members, there are two static variables sum and num, respectively store
the total score and the number of people
➢ There are two common Member functions setdata() and disp() are used to assign
values ​​to data members and output values ​​of data members
respectively. There is also a static member function avg(), which is used to calculate the average score.
The object array is defined in the main() function. to store entered student data

the code

#include "CStud.h"
#include <string.h>
#include <iostream>
using namespace std;
class CStud
{
    
    
private:
	char no[10];//学号
	char name[10];//姓名
	double score;//成绩
	static double sum;//总分
	static int num;//总人数
public:
	//给数据成员赋值
	void setdata(char* _no, char* _name, double _score) {
    
    
		strcpy(no, _no);
		strcpy(name, _name);
		score = _score;
		sum += score;
		num++;
	}
	//输出数据成员的值 
	void disp() {
    
    
		cout << "学号:" << no  << " 姓名:" << name  << " 分数:" << score << endl;
	}
	//计算平均分
	static double avg() {
    
    
		return sum / num;
	}

};

double CStud::sum = 0;
int CStud::num = 0;

int main() {
    
    
	int n;
	cout << "请输入学生人数" << endl;
	cin >> n;
	CStud* stu = new CStud[n];
	cout << "请依次输入学生的学号、姓名和分数" << endl;
	int i;
	for (i = 0; i < n; i++) {
    
    
		char tno[10];
		char tname[10];
		double tscore;
		cin >> tno;
		cin >> tname;
		cin >> tscore;
		stu[i].setdata(tno, tname, tscore);
	}
	for (i = 0; i < n; i++) {
    
    
		stu[i].disp();
	}
	double a = CStud::avg();
	cout << "平均分:" << a << endl;
}

Precautions

If vs2019 reports an error

C4996 ‘strcpy’: This function or variable may be unsafe. Consider using

Then under the precompilation definition under the c++ precompiler, add a new

_CRT_SECURE_NO_WARNINGS
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45184581/article/details/120969403