因为是初学者,例题程序均不是最简便的,可供一看,如有不足以及错误还请指点呐~
一、编写一个基于对象的程序,求圆球的体积,要求:
(1)定义一个圆球类Circle,类内有私有数据成员radius(半径),公有成员函数get_value()、volume()。
(2)get_value()函数和volume()函数在类外定义。get_value()作用是从键盘输入半径的值,volume()的作用是计算圆球的体积并在屏幕上显示。
(圆球体积计算公式为:v=4/3πr3)
(3)在main()函数定义Circle类的对象circle1,并调用get_value()函数给球半径赋值,调用volume()函数输出圆球的体积。
#include<iostream>
using namespace std;
class circle{
public:
void get_value();
void volume();
private:
int radius;
};
void circle:: get_value(){//类外声明
cin>>radius;
}
void circle :: volume(){//类外声明
double a = 4.0/3.0*3.14*radius*radius*radius;
cout<< a;
}
int main(){
circle c1;
c1.get_value();
c1.volume();
}
二、
(1)定义一个日期类Time,类内有私有数据成员hour(小时)、mintue(分钟)、second(秒钟)
(2)set_date()函数set_date()作用是从键盘输入小时、分钟、秒钟的值,通过cout输出最后的结果
(3)在main()函数定义Date类的对象d1,并调用set_ date()函数给日期赋值,调用show_date()函数输出日期的值
#include<iostream>
using namespace std;
class Time{
public:
void set_date(int a,int b,int c){
hour = a;
mintue = b;
second = c;
}
int gethour();
int getmintue();
int getsecond();
private:
int hour,mintue,second;
};
int Time:: gethour(){
return hour;
}
int Time:: getmintue(){
return mintue;
}
int Time:: getsecond(){
return second;
}
int main(){
Time d1;
int h,m,s;
cin>>h>>m>>s;
d1.set_date(h,m,s);
cout<<d1.gethour()<<"时\t"<<d1.getmintue()<<"分\t"<<d1.getsecond()<<"秒\t";
//想用cout输出结果,需要数据成员hour等,但数据成员位于private作用域下,因此通过调用public:中的函数的返回值充当hour等..
return 0;
}
三、编写一个基于对象的程序,求一个有十个数据的整型数组中元素的最大值,要求:
(1)定义一个类Array_max,类内有私有数据成员array[10]、max分别存储十个整数、最大值,公有成员函数set_value()、max_volume()。
(2)set_value()函数和max_volume()函数在类外定义。set_value()作用是从键盘输入数组十个元素的值,max_volume()的作用是求出并显示数组元素的最大值。
(3)在main()函数定义Array_max类的对象arrmax,并调用set_value()函数给数组赋值,调用max_volume()函数求出并显示数组元素的最大值。
#include<iostream>
using namespace std;
class Array_max{
public:
void set_value();
int max_value();
private:
int array[10],max;
};
void Array_max :: set_value(){
for(int i=0;i<10;i++){
cin>>array[i];
}
}
int Array_max :: max_value(){
int i=0,max = i;
for(int j=i+1;j<10;j++){
if(array[max]<array[j]){
max = j;
}
}
if(max!=i){
int temp = array[i];
array[i] = array[max];
array[max] = temp;
}
return array[0];
}
int main(){
Array_max a1;
a1.set_value();
cout<<a1.max_value()<<endl;
}
四、定义盒子 Box类,要求具有以下成员:长、宽、高分别为 length、width、hight ,可计算盒子体积;可计算盒子的表面积。
#include<iostream>
using namespace std;
class Box{
public:
void shape(int m,int n,int l);
int V(int a,int b,int c);
int S(int a,int b,int c);
private:
int length,width,hight;
};
void Box:: shape(int m,int n,int l){
length = m;
width = n;
hight = l;
}
int Box:: V(int a,int b,int c){
return a*b*c;
}
int Box:: S(int a,int b,int c){
int w = 2*a*b+2*a*c+2*b*c;
return w;
}
int main(){
Box b;
int m,n,l;
cin>>m>>n>>l;
b.shape(m,n,l);
cout<<"面积等于"<<b.S(m,n,l)<<" 体积等于"<<b.V(m,n,l)<<endl;
}