实践3

4-11

#include<iostream> using namespace std; //声明定义类rectangle及其数据和方法 class Rectangle{ public: //外部接口 Rectangle(float l,float w); float area(); //计算面积 private: //私有数据成员 float length,width; }; //类的实现 //构造函数初始化数据成员 Rectangle::Rectangle(float l,float w){ length=l,width=w; } //计算矩形面积 float Rectangle::area(){ return length*width; } //主函数实现 int main(){ float length,width; cout<<"enter the length and width of the rectangle:"; cin>>length>>width; Rectangle border(length,width); //计算面积并输出 float result=border.area(); cout<<"area is"<<result<<endl; return 0; }


4-20
#include<iostream> 
#include<cmath>
using namespace std;
class Complex{
    public:
        Complex(double r0=0,double i0=0);
        void add(Complex &c0);
        void show()
        {
            cout<<"complex:"<<Real<<"+"<<imaginary<<"i"<<endl;
        }
        
    private:
        double Real;
        double imaginary; 

};        
//相关成员函数的实现
Complex::Complex(double r0,double i0)
{
    Real=r0;
    imaginary=i0;
}

void Complex::add(Complex &c0)
{
    c0.Real=Real+c0.Real;
    c0.imaginary=imaginary+c0.imaginary;
}
int main()
{
    Complex c1(3,5);     //用复数3+5i初始化c1
    Complex c2=4.5;      //用实数4.5初始化c2
    c1.show();
    c2.show();
    c1.add(c2);          //将c2与c1相加
    cout<<"additon:"<<endl;
    c1.show();           //输出
    return 0;
}

题目不多,但是发现的问题很多,仅实践这两题还不够。

 

posted @ 2018-04-08 22:20  bhys  阅读(129)  评论(3编辑  收藏  举报