正方形作为一类

时间:2015-12-12 17:52:32

标签: c++

该程序声明Square类并使用成员函数来查找正方形的周长和面积

我没弄清楚出了什么问题。我认为大部分都是正确的。 请输入正方形边长 8 广场的面积是81 正方形的周长为36

// This program declares the Square class and uses member functions to find
// the perimeter and area of the square
#include <iostream>

using namespace std;

// FILL IN THE CODE TO DECLARE A CLASS CALLED Square. TO DO THIS SEE
// THE IMPLEMENTATION SECTION.

class Square
{
      private:
        double Length;
      public:
        void setSide(float, double);
        double getArea(double);
        double getPerimeter(double);
};



int main()
{
    Square box;         // box is defined as an object of the Square class
    double side; // size contains the length of a side of the square 
    double Length;


    // FILL IN THE CLIENT CODE THAT WILL ASK THE USER FOR THE LENGTH OF THE SIDE 
    // OF THE SQUARE. (This is stored in size)
    cout << "What is the Length of the side of the square?"<<endl;
    cin >> Length;

    // FILL IN THE CODE THAT CALLS SetSide.
    box.setSide(Length, side);

    // FILL IN THE CODE THAT WILL RETURN THE AREA FROM A CALL TO A FUNCTION
    // AND PRINT OUT THE AREA TO THE SCREEN 
    cout<<"side: "<<side<<endl;
    cout << "The area is "<< box.getArea(side)<<endl;

    // FILL IN THE CODE THAT WILL RETURN THE PERIMETER FROM A CALL TO A 
    // FUNCTION AND PRINT OUT THAT VALUE TO THE SCREEN 
    cout << "The perimeter is " << box.getPerimeter(side)<<endl;
    system("pause");

    return 0;
}

//__________________________________________________________________
//Implementation section Member function implementation

//**************************************************
// setSide
//
// task: This procedure takes the length of a side and
// places it in the appropriate member data
// data in: length of a side
//***************************************************

void Square::setSide(float Length, double side)
{
   Length = side;


}

//**************************************************
// findArea
//
// task: This finds the area of a square
// data in: none (uses value of data member side)
// data returned: area of square
//***************************************************

double Square::getArea()
{
    return Length * Length

}

//**************************************************
// findPerimeter
//
// task: This finds the perimeter of a square
// data in: none (uses value of data member side)
// data returned: perimeter of square
//*************************************************** 

double Square::getPerimeter()
{
    return Length * 4; 

}

2 个答案:

答案 0 :(得分:3)

亲爱的,亲爱的。

  • setSide应该只接受一个参数,并将值存储在成员变量中。
  • setArea应该被称为getAreafindArea。 (我更喜欢“得到”,但在这种情况下,也可以getPerimeter。)
  • getAreagetPerimeter都不应该接受任何参数(并且应该是const成员函数)。
  • 您应该决定全程使用floatdouble。 (如有疑问,请使用double)。

答案 1 :(得分:1)

方8的正方形区域是64 ...你得到什么作为输出?

请粘贴您的实际代码:

 cout << "The area is "<< box.setArea(side)<<endl;

不会使用您粘贴的代码进行编译(其中setArea定义在哪里)