当前位置:   article > 正文

今日学习在线编程题:点到矩形_码蹄集 矩形

码蹄集 矩形

题目来源:码蹄集

https://matiji.net/exam/brushquestion/595/778/B3FCFEC101BD05189BB74D522E019504

 

参考程序

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <math.h>
  5. typedef struct tagPOINT { //
  6. int x, y; //坐标值x和y
  7. } POINT;
  8. typedef struct tagLINE { //线
  9. POINT s, e; //线的两端
  10. } LINE;
  11. typedef struct tagRECT { //矩形
  12. POINT lt, rb; //矩形的左上角和右下角
  13. } RECT;
  14. float distance_pl(POINT p, LINE l) {
  15. float d = (l.s.y - l.e.y)*p.x + (l.e.x - l.s.x)*p.y + (l.s.x*l.e.y - l.e.x*l.s.y);
  16. d = fabs(d) / sqrt((l.e.x - l.s.x)*(l.e.x - l.s.x) + (l.e.y - l.s.y)*(l.e.y - l.s.y));
  17. return d;
  18. }
  19. float distance_pp(POINT p, POINT l) {
  20. float d = sqrt((p.x - l.x)*(p.x - l.x) + (p.y - p.y)*(p.y - p.y));
  21. return d;
  22. }
  23. int main()
  24. {
  25. RECT rect;
  26. POINT p;
  27. float d, k1, k2;
  28. int ret;
  29. ret = scanf("%d %d", &rect.lt.x, &rect.lt.y);
  30. ret = scanf("%d %d", &rect.rb.x, &rect.rb.y);
  31. ret = scanf("%d %d", &p.x, &p.y);
  32. if (rect.lt.x <= p.x&&p.x <= rect.rb.x && rect.rb.y <= p.y&&p.y <= rect.lt.y) {
  33. printf("0");
  34. }
  35. else {
  36. LINE l1, l2; float dist_min; POINT tmp;
  37. //矩形x范围内上方或下方
  38. if (rect.lt.x <= p.x&&p.x <= rect.rb.x) {
  39. l1.s = rect.lt;
  40. l1.e = l1.s; l1.e.x = rect.rb.x;
  41. dist_min = distance_pl(p, l1);
  42. l2.s = rect.rb;
  43. l2.e = l2.s; l1.e.x = rect.lt.x;
  44. dist_min = fmin(dist_min, distance_pl(p, l2));
  45. printf("%d", (int)(floor(dist_min)));
  46. return 0;
  47. }
  48. //矩形y范围内左侧或右侧
  49. if (rect.lt.x <= p.x&&p.x <= rect.rb.x) {
  50. l1.s = rect.lt;
  51. l1.e = l1.s; l1.e.y = rect.rb.y;
  52. dist_min = distance_pl(p, l1);
  53. l2.s = rect.rb;
  54. l2.e = l2.s; l1.e.x = rect.lt.x;
  55. dist_min = fmin(dist_min, distance_pl(p, l2));
  56. printf("%d", (int)(floor(dist_min)));
  57. return 0;
  58. }
  59. //其他情况,取最近的顶点距离作为距离
  60. dist_min = distance_pp(p, rect.lt);
  61. dist_min = fmin(dist_min, distance_pp(p, rect.rb));
  62. tmp = rect.lt; tmp.x = rect.rb.x;
  63. dist_min = fmin(dist_min, distance_pp(p, tmp));
  64. tmp = rect.lt; tmp.y = rect.rb.y;
  65. dist_min = fmin(dist_min, distance_pp(p, tmp));
  66. printf("%d", (int)(floor(dist_min)));
  67. }
  68. return 0;
  69. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/392587
推荐阅读
相关标签
  

闽ICP备14008679号