c++设计一个名为Rectangle的矩形类,其属性为矩形的左上角和右下角两个点的坐标,能计算和输出矩形的周长与面积。
作者:野牛程序员:2024-10-25 10:48:52 C++阅读 2658
c++设计一个名为Rectangle的矩形类,其属性为矩形的左上角和右下角两个点的坐标,能计算和输出矩形的周长与面积。
c++设计一个名为Rectangle的矩形类,其属性为矩形的左上角和右下角两个点的坐标,能计算和输出矩形的周长与面积。
以下是一个 C++ 程序,设计了一个名为 Rectangle 的矩形类,具有计算和输出矩形周长与面积的功能:
#include <iostream>
class Point {
public:
double x; // x 坐标
double y; // y 坐标
Point(double xCoord, double yCoord) : x(xCoord), y(yCoord) {}
};
class Rectangle {
private:
Point topLeft; // 矩形的左上角
Point bottomRight; // 矩形的右下角
public:
// 构造函数
Rectangle(double x1, double y1, double x2, double y2)
: topLeft(x1, y1), bottomRight(x2, y2) {}
// 计算周长
double perimeter() {
double length = bottomRight.x - topLeft.x;
double width = topLeft.y - bottomRight.y;
return 2 * (length + width);
}
// 计算面积
double area() {
double length = bottomRight.x - topLeft.x;
double width = topLeft.y - bottomRight.y;
return length * width;
}
// 输出矩形的信息
void display() {
std::cout << "矩形的左上角: (" << topLeft.x << ", " << topLeft.y << ")" << std::endl;
std::cout << "矩形的右下角: (" << bottomRight.x << ", " << bottomRight.y << ")" << std::endl;
std::cout << "周长: " << perimeter() << std::endl;
std::cout << "面积: " << area() << std::endl;
}
};
int main() {
// 创建一个矩形实例
Rectangle rect(1.0, 4.0, 5.0, 1.0);
// 输出矩形的信息
rect.display();
return 0;
}程序说明
Point 类: 用于表示矩形的两个顶点(左上角和右下角)的坐标。
包含
x和y坐标,并提供构造函数进行初始化。Rectangle 类: 包含矩形的属性和方法。
构造函数: 用于初始化矩形的两个顶点。
perimeter 方法: 计算矩形的周长。
area 方法: 计算矩形的面积。
display 方法: 输出矩形的顶点坐标、周长和面积。
main 函数: 创建
Rectangle类的实例并调用display方法输出信息。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

