编写程序,已有若干学生的数据,包括:学号、姓名、某门课的成绩,要求输出这些学生的信息,并计算出学生总人数和平均成绩(要求将学生总人数和总成绩用静态数据成员表示,对静态数据成员的操作用静态成员函数,若干学生对象用对象数组表示,输出学生信息用循环)。
代码1:
#include<iostream>
#include<string>
using namespace std;
class student {
public:
void show() {
cout<<"学号 "<<num<<"姓名 "<<name<<"成绩 "<<score<<endl;
}
static void show1() {
cout<<"学生总人数为:"<<count<<endl;
cout<<"平均分为:"<<aver<<endl;
}
student(string num1,string name1,double score1) {
num=num1;
name=name1;
score=score1;
count++;
sum+=score1;
aver=sum/count;
}
private:
string num;
string name;
double score;
static double sum;
static int count;
static double aver;
};
double student::sum=0.0;
int student::count=0;
double student::aver=0.0;
int main() {
student stu1("2019001","张三",78);
stu1.show();
student stu2("2019105","李四",85);
stu2.show();
student stu3("2019128","王五",67);
stu3.show();
student stu4("2019341","赵六",75);
stu4.show();
student::show1();
return 0;
}
运行结果1:
代码2:
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
class Student {
private:
string Sno;
string Sname;
int Sscore;
static int Snum;
static int Stotalscore;
public:
Student(string no,string name,int score);
void print();
static void printstatic();
static int getSnum();
};
int Student::Snum=0;
int Student::Stotalscore=0;
Student::Student(string no,string name,int score) {
Sno=no;
Sname=name;
Sscore=score;
Snum++;
Stotalscore+=score;
}
void Student::print() {
cout<<setw(10)<<Sno<<setw(10)<<Sname<<setw(10)<<Sscore<<endl;
}
void Student:: printstatic() {
cout<<"学生总人数为:"<<Snum<<endl;
cout<<"平均分为:"<<(double)Stotalscore/Snum<<endl;
}
int Student::getSnum() {
return Snum;
}
int main() {
Student s[]= {
Student("2019001","张三",78),
Student("2019105","李四",85),
Student("2019128","王五",67),
Student("2019341","赵六",75)
};
cout<<left;
cout<<setw(10)<<"学号"<<setw(10)<<"姓名"<<setw(10)<<"成绩"<<endl;
for(int i=0; i<Student::getSnum(); i++)
s[i].print();
Student::printstatic();
}
运行结果2: