编写一个c++程序,测试一个名为rectangle的矩形类,其属性为矩形的左下角与右上角两个点的坐标,能计算矩形的面积
时间: 2024-05-16 21:17:16 浏览: 28
以下是一个简单的C++程序,用于测试Rectangle类并计算矩形面积:
```c++
#include <iostream>
using namespace std;
class Rectangle {
public:
Rectangle(double x1, double y1, double x2, double y2) {
this->x1 = x1;
this->y1 = y1;
this->x2 = x2;
this->y2 = y2;
}
double getArea() {
return (x2 - x1) * (y2 - y1);
}
private:
double x1, y1, x2, y2;
};
int main() {
Rectangle r(0, 0, 4, 5);
cout << "The area of the rectangle is: " << r.getArea() << endl;
return 0;
}
```
这个程序定义了一个名为Rectangle的类,它有四个属性:矩形左下角的x和y坐标以及右上角的x和y坐标。这个类还有一个getArea()函数,用于计算矩形的面积。在main()函数中,我们创建了一个Rectangle对象r,它的左下角坐标是(0, 0),右上角坐标是(4, 5)。我们调用r.getArea()函数,并输出结果。最终输出的结果是矩形的面积,即20。
相关问题
用C++设计并测试一个名为Rectangle的矩形类,其属性为矩形的左下角与右上角两个点的坐标,能计算矩形的面积。
好的,以下是一个简单的Rectangle类的代码:
```c++
#include <iostream>
using namespace std;
class Rectangle {
public:
Rectangle(int x1, int y1, int x2, int y2) {
this->x1 = x1;
this->y1 = y1;
this->x2 = x2;
this->y2 = y2;
}
int getArea() {
return abs(x2 - x1) * abs(y2 - y1);
}
private:
int x1, y1, x2, y2;
};
int main() {
Rectangle rect(0, 0, 5, 5);
cout << "The area of the rectangle is: " << rect.getArea() << endl;
return 0;
}
```
这个类接受四个整数参数,分别表示矩形左下角和右上角的坐标。getArea() 方法计算并返回矩形的面积。在 main() 函数中,我们创建了一个 Rectangle 对象并输出其面积。
定义一个名为rectangle的矩形类,其属性为矩形的左下角与右上角两个点的坐标,成员函数getarea()功能为计算矩形的面积。
以下是一个使用C++编写的矩形类 `Rectangle`示例代码,其中包括属性为矩形的左下角与右上角两个点的坐标,并且有一个成员函数 `getArea()` 用于计算矩形的面积:
```cpp
#include <iostream>
class Rectangle {
private:
int x1, y1; // 左下角坐标
int x2, y2; // 右上角坐标
public:
Rectangle(int x1, int y1, int x2, int y2) {
this->x1 = x1;
this->y1 = y1;
this->x2 = x2;
this->y2 = y2;
}
int getArea() {
int width = x2 - x1;
int height = y2 - y1;
return width * height;
}
};
int main() {
int x1, y1, x2, y2;
std::cout << "Enter the coordinates of the bottom-left point: ";
std::cin >> x1 >> y1;
std::cout << "Enter the coordinates of the top-right point: ";
std::cin >> x2 >> y2;
Rectangle rect(x1, y1, x2, y2);
int area = rect.getArea();
std::cout << "The area of the rectangle is: " << area << std::endl;
return 0;
}
```
在这段代码中,`Rectangle` 类具有私有属性 `x1`, `y1`, `x2`, `y2`,分别表示矩形的左下角和右上角的坐标。构造函数用于初始化这些属性。`getArea()` 函数计算矩形的宽度和高度,并返回其面积。
在 `main` 函数中,我们首先输入矩形的左下角和右上角的坐标。然后,我们创建一个 `Rectangle` 对象,并调用 `getArea()` 函数来计算矩形的面积,并将其打印出来。
请注意,为了简化示例,这段代码没有进行输入验证。在实际应用中,您可能需要添加输入验证以确保输入的正确性。