用c++编写一个矩形类,已知两点求面积和周长
时间: 2024-02-18 10:34:51 浏览: 37
好的,我知道了。这里是用 C 语言编写的一个简单的矩形类,可以根据两点来计算矩形的面积和周长:
```c
#include <stdio.h>
#include <math.h>
struct point {
float x;
float y;
};
struct rectangle {
struct point pt1;
struct point pt2;
};
float distance(struct point a, struct point b) {
float dx = a.x - b.x;
float dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
float perimeter(struct rectangle rect) {
float width = distance(rect.pt1, rect.pt2);
float height = distance((struct point){rect.pt1.x, rect.pt2.y}, (struct point){rect.pt2.x, rect.pt1.y});
return 2 * (width + height);
}
float area(struct rectangle rect) {
float width = distance(rect.pt1, rect.pt2);
float height = distance((struct point){rect.pt1.x, rect.pt2.y}, (struct point){rect.pt2.x, rect.pt1.y});
return width * height;
}
int main() {
struct rectangle rect = {{0,0},{2,2}};
printf("The perimeter of the rectangle is %f\n", perimeter(rect));
printf("The area of the rectangle is %f\n", area(rect));
return 0;
}
```
在这个示例中,我们首先定义了一个 `point` 结构体来表示二维平面上的一个点,然后定义了一个 `rectangle` 结构体来表示一个由两个点确定的矩形。接下来我们实现了一个 `distance` 函数来计算两个点之间的距离,这个函数用到了勾股定理。最后我们定义了 `perimeter` 和 `area` 函数来分别计算矩形的周长和面积,这里用到了上面定义的 `distance` 函数。
在 `main` 函数中,我们定义了一个矩形 `rect`,并且输出了它的周长和面积。
希望这个示例能够帮助你理解如何用 C 语言编写简单的矩形类!