赞
踩
(2)C++基本数据类型和函数的定义和使用
编写C++程序,实现:
①给定任意一个点P和一条线段AB,计算点P到AB的最短距离;
图1 点到直线最短距离示意图
计算点到线段最短距离的算法描述:
1)计算向量A->P,A->B;
2)定义r1=|AP|cos(a) = dot((A->P)( A->B))/|AB|,表示向量A->P在A->B方向上的投影长度;其中,a是向量A->P与A->B的夹角;dot()是向量点乘;
3)定义r2=r1/|AB|,如果r2<=0,则P为图1中中间情形,即点P到AB的最短距离记为|AP|;
4)如果r2>=1,即P为图1中最右边的情形,即点P到AB的最短距离记为|PB|;
5)r2为其他取值时,P为图1中最左边情形,即点P到AB的最短距离记为sqrt(|AP|2-r12)。
基于以上函数,实现给定任意一个点计算起到任意多段线(即线段的集合,polyline)的最短距离。
- #include <iostream>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
-
- #define random(x) (rand()%x)
- typedef struct tagPoint
- {
- double x;
- double y;
- }Point;
-
-
- double PFT(Point a,Point b,Point p)
- {
- double ap = (b.x - a.x) * (p.x - a.x) + (b.y - a.y) * (p.y - a.y);
- if (ap <= 0)
- return sqrt((p.x - a.x) * (p.x - a.x) + (p.y - a.y) * (p.y - a.y));//最短为ap
- double ab = (b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y);
- if (ap >= ab)
- return sqrt((p.x - b.x) * (p.x - b.x) + (p.y - b.y) * (p.y - b.y));//最短为bp
- double r = ap / ab;
- double px = a.x + (b.x - a.x) * r;
- double py = a.y + (b.y - a.y) * r;
- double L1=sqrt((p.x - px) * (p.x - px) + (p.y - py) * (p.y - py));//垂线距离
- cout << "点到线段最小距离为:" << L1<<endl;
- }
-
- double QFT(Point q)
- {
- srand((unsigned)time(NULL));
- int point_num = 20;
- Point* Polyline = new Point[point_num];
- for (int i = 0; i < point_num; i++)
- {
- Polyline[i].x = random(100);
- Polyline[i].y = random(100);
- }
-
- double d1, d2;
- for (int i = 0; i < point_num; i++)
- {
- d1 = PFT(Polyline[i], Polyline[i + 1], q);
- d2 = PFT(Polyline[i + 1], Polyline[i + 2], q);
- if (d1 < d2)
- return d1;
- else
- return d2;
- }
- delete []Polyline;
-
- }
-
- int main()
- {
- double L2;
- Point a, b, c, q;
- cout << "请输入A点的坐标" << endl;
- cin >> a.x >> a.y;
- cout << "请输入B点的坐标" << endl;
- cin >> b.x >> b.y;
- cout << "请输入C点的坐标" << endl;
- cin >> c.x >> c.y;
- PFT(a, b, c);
- cout << "请输入点的坐标" << endl;
- cin >> q.x >> q.y;
- L2 = QFT(q);
- cout <<"点到多线段的最短距离为:"<< L2;
- return 0;
- }
我的思路
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。