编写程序:
求若干个学生某门课的平均成绩
要求:
定义一个Student类,其中包括如下内容:
私有数据成员:
1、非静态数据成员:double score; //存某门课的成绩
2、静态数据成员:double total和int count //总分和学生人数
公有成员方法:
1、普通成员函数:scoreTotal(double s) //用户设置分数、求总分和累计学生人数
2、静态成员函数:
int person() //用于返回学生人数
double average()//用于返回求得的平均分
请给出Student类的完整定义。
输入:
无
输出:
学生人数:3
平均分:87.6667
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36#include<iostream> #include<cstring> using namespace std; class Student{ private: double score=0;//某课成绩 static double total;//总分 static int count;//人数 public: void scoreTotal(double s){ score=s; total+=s;//累计成绩 count++;//人数增加 } static int person(){ return count; } static double average(){ return total/count;//平均分 } }; double Student::total=0.0;//静态数据成员初始化必须在类外进行 //形式为: 类型 类名::静态数据成员名=初始值; int Student::count=0; int main(){ Student st[2]; st[0].scoreTotal(98); st[1].scoreTotal(88); Student t; t.scoreTotal(77); cout<<"学生人数:"<<Student::person()<<endl; cout<<"平均分:"<<Student::average()<<endl; return 0; }
编写程序:
假设圆柱体的高是一个固定值,则体积的大小完全由半径来调整。定义个Cylinder类,
包含:
私有数据成员
常数据成员:
double high;
double PI;
普通数据成员:
double r;
公有方法
1、构造函数:
Cylinder(double radius,double h)
提示:(常数据成员初始化需要在初始化列表中进行,PI(3.14159)直接初始化)
2、常函数:计算圆柱体体积
double volumn() const
输入:
无
输出:
31.4159
1210.35
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25#include<iostream> #include<string> using namespace std; class Cylinder{ private: const double high;//常数据成员 const double PI=3.14159; double r; public: Cylinder(double radius,double h):high(h){//初始化列表 //high=h;//常变量只能在初始化列表初始化 r=radius; } double volumn() const{ return PI*r*r*high; } }; int main(){ //第一个参数是半径,第二个参数是高 Cylinder c1(1,10),c2(7.98,6.05); cout<<c1.volumn()<<endl; cout<<c2.volumn()<<endl; return 0; }
最后
以上就是如意小霸王最近收集整理的关于【C++学习笔记8】实验8-类与对象知识进阶(2)的全部内容,更多相关【C++学习笔记8】实验8-类与对象知识进阶(2)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复