用C++设计point坐标类(x,y坐标),完成程序录入,调试,运行。计算point类的内存大小,试编写程序,计算point对象p1,p2的距离。
时间: 2024-05-09 11:20:22 浏览: 11
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
double x;
double y;
} point;
int main() {
// 创建两个点对象
point p1 = {1.0, 2.0};
point p2 = {3.0, 4.0};
// 计算点对象占用的内存大小
printf("point占用的内存大小为:%ld bytes\n", sizeof(point));
// 计算两个点之间的距离
double dist = sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));
printf("p1和p2之间的距离为:%lf\n", dist);
return 0;
}
```
输出结果:
```
point占用的内存大小为:16 bytes
p1和p2之间的距离为:2.828427
```
相关问题
用c++语言sort函数对Point类的坐标排序
假设Point类的定义如下:
```
typedef struct Point {
int x;
int y;
} Point;
```
可以使用sort函数对Point类的坐标进行排序,代码如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Point {
int x;
int y;
} Point;
int compare(const void *a, const void *b) {
Point *p1 = (Point *)a;
Point *p2 = (Point *)b;
if (p1->x != p2->x) {
return p1->x - p2->x;
} else {
return p1->y - p2->y;
}
}
int main() {
Point points[] = {{1, 2}, {3, 1}, {2, 3}, {1, 3}, {3, 2}};
int n = sizeof(points) / sizeof(points[0]);
qsort(points, n, sizeof(Point), compare);
for (int i = 0; i < n; i++) {
printf("(%d, %d) ", points[i].x, points[i].y);
}
printf("\n");
return 0;
}
```
输出结果为:
```
(1, 2) (1, 3) (2, 3) (3, 1) (3, 2)
```
其中,compare函数用于指定排序的比较方式,先按照x坐标排序,如果x坐标相同,则按照y坐标排序。qsort函数是C标准库中的快速排序函数,用于对数组进行排序。
c++ 中提取cv::Point类型数据中的x与y坐标
在C++中,可以通过以下方式从cv::Point类型数据中提取x和y坐标:
```c++
cv::Point pt(10, 20); // 创建一个cv::Point对象
int x = pt.x; // 获取x坐标
int y = pt.y; // 获取y坐标
```
这里我们首先定义了一个cv::Point对象pt,并初始化其x和y坐标分别为10和20。然后,我们使用pt.x和pt.y分别获取其x和y坐标,并将其分别赋值给变量x和y。