Advertisement
Infernale

NCTU LAB 02/04 NUM 1

Apr 2nd, 2019
448
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <iostream>
  2. #include <ctime>
  3. #include <cstdlib>
  4. #include <cmath>
  5. using namespace std;
  6.  
  7. #define dist(x1, y1, x2, y2) sqrt(pow((x2-x1),2)+pow((y2-y1),2))
  8.  
  9. struct Point{
  10.     int x, y;
  11. }points;
  12.  
  13. struct pointSet{
  14.     int n;
  15.     Point *pt;
  16. }pSet;
  17.  
  18. int n, x, y;
  19.  
  20.  
  21. void genPoints(pointSet &ps, int n){
  22.     ps.pt = new Point[n];
  23.     srand(time(0));
  24.     for(int i=0;i<n;i++){
  25.         ps.pt[i].x = rand()%201 - 100;
  26.         ps.pt[i].y = rand()%201 - 100;
  27.     }
  28. }
  29.  
  30. Point match(Point p, pointSet ps){
  31.     int minX, minY;
  32.     double distance = 10e9;
  33.     for(int i=0;i<n;i++){
  34.         if(dist(x, y, ps.pt[i].x, ps.pt[i].y)<distance){
  35.             distance = dist(x, y, ps.pt[i].x, ps.pt[i].y);
  36.             minX = ps.pt[i].x;
  37.             minY = ps.pt[i].y;
  38.         }
  39.     }
  40.     cout << endl;
  41.     printf("The nearest point to (%d,%d) is (%d,%d)\n", x, y, minX, minY);
  42. }
  43.  
  44. int main(){
  45.     cout << "Input the number of points and the testing point (x,y): " << endl;
  46.     while(cin >> n >> x >> y){
  47.         genPoints(pSet, n);
  48.         cout << "The points are: " << endl;
  49.         for(int i=0;i<n;i++){
  50.             cout << "(" << pSet.pt[i].x << "," << pSet.pt[i].y << ")" << endl;
  51.         }
  52.         match(points, pSet);
  53.         cout << endl;
  54.         cout << "Input the number of points and the testing point (x,y): " << endl;
  55.     }
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement