用c语言编写函数retangle(a,b,
时间: 2023-05-19 19:03:47 浏览: 162
c,d),实现计算矩形的面积和周长,其中a、b、c、d分别为矩形的两个对角线端点的坐标。
以下是实现该函数的代码:
```c
#include <stdio.h>
#include <math.h>
struct Point {
double x, y;
};
struct Rectangle {
struct Point p1, p2;
};
double distance(struct Point p1, struct Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return sqrt(dx * dx + dy * dy);
}
double rectangle_area(struct Rectangle r) {
double width = distance(r.p1, (struct Point){r.p2.x, r.p1.y});
double height = distance(r.p1, (struct Point){r.p1.x, r.p2.y});
return width * height;
}
double rectangle_perimeter(struct Rectangle r) {
double width = distance(r.p1, (struct Point){r.p2.x, r.p1.y});
double height = distance(r.p1, (struct Point){r.p1.x, r.p2.y});
return 2 * (width + height);
}
void rectangle(struct Point p1, struct Point p2) {
struct Rectangle r = {p1, p2};
printf("Area: %f\n", rectangle_area(r));
printf("Perimeter: %f\n", rectangle_perimeter(r));
}
int main() {
struct Point p1 = {0, 0};
struct Point p2 = {3, 4};
rectangle(p1, p2);
return 0;
}
```
该函数接受四个参数a、b、c、d,分别表示矩形的两个对角线端点的坐标。函数中定义了两个结构体Point和Rectangle,分别表示点和矩形。distance函数用于计算两个点之间的距离,rectangle_area函数用于计算矩形的面积,rectangle_perimeter函数用于计算矩形的周长。最后在main函数中调用rectangle函数,传入两个点的坐标,输出矩形的面积和周长。
阅读全文