用类求总分和平均分
聲明一個Student類,在該類中包括一個數據成員score(分數)、兩個靜態數據成員total_score(總分)和count(學生人數);還包括一個成員函數account()用于設置分數、累計學生的成績之和、累計學生人數,一個靜態成員函數sum()用于返回學生的成績之和,另一個靜態成員函數average()用于求全部成績的平均值。在main函數中,輸入某班同學的成績,并調用上述函數求出全班同學的成績之和和平均分。
#include<iostream> using namespace std; class Student {public:void account(); //定義一個輸入成績和計算總分的成員函數; static double sum();//返回總分; static double average();//返回平均值; private:double score;static double total_score;static int count; }; void Student::account() {cin>>score;//輸入成績; total_score+=score;//計算總分; count++;//統計人數; } double Student::sum() {return total_score; } double Student::average() {return total_score/count; } int Student::count=0;//靜態變量賦初值; double Student::total_score=0; int main() {Student a1;for(int i=0;i<3;i++)a1.account();cout<<"總分是:"<<a1.sum()<<endl;cout<<"平均分是:"<<a1.average()<<endl;return 0; }總結
- 上一篇: 一个简单函数的反汇编分析
- 下一篇: 显示字符串