【3.22】声明一个Circle类,有数据成员radius(半径)、成员函数area(),计算圆的面积,构造一个Circle的对象进行测试。
#include<iostream>
using namespace std;const double PI = 3.13;
class Circle
{
public:
Circle(double d)
{
r = d;
}
double area()
{
return PI*r*r;
}
void display();
private:
double r;
};
void Circle::display()
{
cout << "圆的半径是:" << r << endl;
cout << "圆的面积是:" << area() << endl;
}
int main()
{
Circle c1(4);
c1.display();
system("pause");
return 0;
}
【3.23】建立类cylinder,cylinder的构造函数被传递了两个double值,分别表示圆柱体的半径和高度。用类cylinder计算圆柱体的体积,并存储在一个double 变量中。在类cylinder中包含一个成员函数vol,用来显示每个cylinder对象的体积。
#include<iostream>
using namespace std;
const double PI = 3.13;
class cylinder
{
public:
cylinder()
{
r = 0;
high = 0;
}
cylinder(double a,double b)
{
r = a;
high = b;
}
double countvol()
{
double vol;
vol=PI*r*r*high;
return vol;
}
void vol();
private:
double r;
double high;
};
void cylinder::vol()
{
cout << "圆的半径是:" << r <<" "<<"圆的高度是:"<<high<< endl;
cout << "圆的体积是:" << countvol() << endl;
}
int main()
{
cylinder c1(4,6);
c1.vol();
system("pause");
return 0;
}
【3.24】定义一个日期类Date,该类对象存放一个日期,可以提供的操作有:
void :printDate(); //显示日期,格式如“日期是:2010年6月8日”
void GetYear(); //取年的值
void GetMonth(); //取月的值
void GetDay(); //取日的值
void SetDate(int Y,int m,int d), //设置日期值
还允许对日期对象作以下定义:
Date d1(2010,6,8); //用所给日期定义一个日期变量
Date d2; //定义一个日期对象
Date d3(d1); //用已有的日期构造一个新的对象
要求每一个成员函数都要被调用。
#include<iostream>
using namespace std;
class Date
{
public:
void setDate(int Y, int m, int d)
{
year = Y;
month = m;
day = d;
}
void GetYear();
void GetMonth();
void GetDay();
void printDate();
private:
int year;
int month;
int day;
};
void Date::printDate()
{
cout << "日期是:" << year << "年" << month << "月" << day << "日";
};
int main()
{
Date d1(2014,4,1);
d1.printDate;
Date d2;
d2.printDate;
Date d3(d1);
d3.printDate;
system("pause");
return 0;
}
2.设计一个4*4魔方程序,让魔方的各行值得和等于各列值得和,并且等于两对角线值得和。
#include<iostream>
#include<iomanip>
using namespace std;
class magic
{
public:
magic(int a,int b)
{
first=a;
step=b;
}
void setfirstmagic()
{
first=-1;
int i,j;
for(i=0;0<4;i++)
for(j=0;j<4;j++)
{
m[i][j]=first+step;
first=m[i][j];
}
for(i=0;i<4;i++)
for(j=0;j<4;j++)
cout<<setw(20)<<m[i][j];
}
void generatemagic()
{
sum=m[0][0]+m[3][3];
int a,b;
for(a=0;a<4;a++)
m[a][a]=sum-m[a][a];
for(a=3,b=0;a>=0,b<4;a--,b++)
m[a][b]=sum-m[a][b];
}
void printmagic()
{
int c,d;
for(c=0;c<4;c++)
for(d=0;d<4;d++)
cout<<setw(20)<<m[c][d];
}
private:
int m[4][4];
int step;
int first;
int sum;
};
int main()
{
magic m1(1,2);
cout<<" this is the firstmagic:"<<endl;
cout<<endl;
m1.setfirstmagic();
cout<<endl;
cout<<" this is the generatemagic:"<<endl;
cout<<endl;
m1.generatemagic();
m1.printmagic();
return 0;
}