今天完成了c++作业,在编程的过程中遇到了问题,在博客上将题目记录下来
1.题目要求:求圆的面积,数据成员为半径r,定义为私有成员,要求用成员函数实现在键盘上输入圆半径,计算圆面积、输出圆面积三个功能,要求三个成员函数在类内声明,在类外定义
#include<iostream> #define PI 3.1415926 using namespace std; class circle1{ private: double r; public: circle1(){}; circle1(double r){r=r;}; ~circle1(){cout<<"r:"<<r<<endl;}; void setR(); double getR(){return r;}; void print(double r); void count(double r); }; void circle1::setR(){ cout<<"请输入圆的半径:"<<endl; cin>>r; } void circle1::count(double r){ double s; s=PI*r*r; } void circle1::print(double r){ cout<<"请输出圆的面积:"<<PI*r*r<<endl; } int main(){ circle1 c; c.setR(); double r=c.getR(); c.count(r); c.print(r); return 0; }
2.题目要求:定义一个点类,类名为point,将其坐标x,y,z定义为私有成员,定义两个构造函数(一个不带参数,一个带参数,初始化点的坐标);定义析构函数(输出相关信息,显示析构函数的调用顺序);定义五个公有函数完成点的输入、输出、获得x坐标、获得y坐标和获得z坐标的功能。在主程序中定义该类的一个对象,做到能够输入坐标,输出坐标,并且输出该点到原点的距离
#include<iostream> #include<math.h> using namespace std; class point{ private: int x,y,z; public: point(){}; point(int m,int n,int q){x=m;y=n;z=q;}; ~point(){cout<<"x:"<<x<<",y:"<<y<<",z:"<<z<<endl;}; void setpoint();//点的输入 void inout(int x,int y,int z);//点的输出 int getx(){return x;}; int gety(){return y;}; int getz(){return z;}; }; void point::setpoint(){ cout<<"请输入x:"<<endl; cin>>x; cout<<"请输入y:"<<endl; cin>>y; cout<<"请输入z:"<<endl; cin>>z; } void point::inout(int x,int y,int z){ cout<<"x="<<x<<",y="<<y<<",z="<<z<<endl; } int main(){ point mpoint; mpoint.setpoint(); int x=mpoint.getx(); int y=mpoint.gety(); int z=mpoint.getz(); mpoint.inout(x,y,z); cout<<"该点到原点的距离为:"<<sqrt(x*x+y*y+z*z)<<endl; return 0; }