如何使用类计算Circle和Square的面积? (C ++)

时间:2017-07-27 16:07:39

标签: c++

我正在尝试使用类来计算正方形或圆形的面积(因此,我有5个文件:main.cppsquare.hsquare.cppcircle.h ,和circle.cpp)我的程序正在运行,但计算只显示" 0"该地区。我是C ++的新手(所以对类来说更新)。任何帮助是极大的赞赏。以下是我到目前为止所做的事情:

的main.cpp

#include <iostream>
#include "Square.h"
#include "Circle.h"


using namespace std;

int main()
{

double radius = 0;
int length = 0;
Square square;
Circle circle;
int ch;

cout << "*** Press 1 or 2 on which shape's area you would like to calculate 
***\n\n1.) Area of circle\n2.) Area of square" << endl;
cout << "\nEnter your choice: " << endl;
cin >> ch;

switch(ch)
{
case 1:
{
    cout << "\nEnter radius of the circle: ";
    cin >> radius;
    cout << "\nThe Area of the circle is "<< circle.getArea();
    break;
}
case 2:
{
    cout << "\nPlease Enter the length of the Square's side: ";
    cin >> length;
    cout << "\The Area of the square is "<< square.getArea();
    break;
}

default: cout<<"\n Please enter a valid choice!";
break;
}

return 0;
}

square.h

using namespace std;

class Square
{
private:
int length, area;

public:
Square(int length = 0);
int getLength()const;
void setLength(int length);
int getArea() const;
};

square.cpp

#include <cmath>
#include <iostream>
#include "Square.h"

using namespace std;

Square::Square(int len)
{
length = len;
}
int Square::getLength()const
{
return length;
}
void Square::setLength(int len)
{
length = len;
}
int Square::getArea() const
{
return length * length;
}

circle.h

using namespace std;

class Circle
{
private:
double radius, area;

public:
Circle(double radius = 0);

double getRadius()const;
void setRadius(double radius);
double getArea()const;

};

circle.cpp

#include <cmath>
#include <iostream>
#include "Circle.h"

using namespace std;

Circle::Circle(double r)
{
radius = r;
}
double Circle::getRadius()const 
{
return radius;
}
void Circle::setRadius (double r)
{
radius = r;
}
double Circle::getArea() const 
{
return radius * radius * 3.1415926;
}

1 个答案:

答案 0 :(得分:0)

在使用时,您实际上从未设置过方形的长度,也没有设置圆的半径:

cin >> length;

和..

cin >> radius;

你永远不会打电话给square.setLength(length);circle.setRadius(radius),这两个值的默认参数都是0 ......任何乘以0的都是0。

如果您使用调试器,它将允许您单步执行代码,因此您可以注意变量的值,并更容易地捕获这样的错误。我建议查看调试器通常与编译器一起使用的内容,然后学会使用它。