1. 程式人生 > >3-4 計算長方形的周長和面積

3-4 計算長方形的周長和面積

const 拷貝構造 memory ret snippet gin margin html pri

3-4 計算長方形的周長和面積

Time Limit: 1000MS Memory limit: 65536K

題目描寫敘述

通過本題的練習能夠掌握拷貝構造函數的定義和用法。 設計一個長方形類Rect。計算長方形的周長與面積。

類中有私有數據成員Length(長)、Width(寬),由具有缺省參數值的構造函數對其初始化,函數原型為:Rect(double Length=0, double Width=0); 再為其定義拷貝構造函數,形參為對象的常引用,函數原型為:Rect(const Rect &); 編寫主函數,創建Rect對象r1初始化為長、寬數據,利用r1初始化還有一個Rect對象r2。分別輸出對象的長和寬、周長和面積。 要求: 創建對象 Rect r1(3.0,2.0),r2(r1);

輸入

輸入兩個實數,中間用一個空格間隔。代表長方形的長和寬

輸出

共同擁有6
分別輸出r1的長和寬。 r1的周長; r1的面積;r2的長和寬。 r2的周長。 r2的面積;註意單詞與單詞之間用一個空格間隔

演示樣例輸入

56 32

演示樣例輸出

the length and width of r1 is:56,32
the perimeter of r1 is:176
the area of r1 is:1792
the length and width of r2 is:56,32
the perimeter of r2 is:176
the area of r2 is:1792

提示

輸入 -7.0 -8.0

輸出

the length and width of r1 is:0,0

the perimeter of r1 is:0

the area of r1 is:0

the length and width of r2 is:0,0

the perimeter of r2 is:0

the area of r2 is:0

來源

黃晶晶

演示樣例程序



#include <iostream>
using namespace std;
class Rect
{
private:
    double len;
    double wid;
public:
    Rect(double x=0,double y=0);
    Rect(const Rect &b);
    const void display()
    {
        cout << "the length and width of r1 is:" << len << ","<< wid << endl;
        cout << "the perimeter of r1 is:" << (len + wid) * 2<<endl;
        cout << "the area of r1 is:" << len * wid << endl;
    }
    const void display1()
    {
        cout << "the length and width of r2 is:" << len << ',' << wid<< endl;
        cout << "the perimeter of r2 is:" << (len + wid) * 2 << endl;
        cout << "the area of r2 is:" << len * wid << endl;
    }
};
Rect::Rect(double x,double y)
{
    len=x;
    wid=y;
}
Rect::Rect(const Rect &b)
{
    len=b.len;
    wid=b.wid;
}
int main()
{
    double x,y;
    cin>>x>>y;
    if(x<0||y<0)
    {
        x=0;
        y=0;

    }
    Rect rect(x,y);
    Rect rect1=rect;
    rect.display();
    rect1.display1();
    return 0;
}



3-4 計算長方形的周長和面積