点、线、三角形.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <iostream>
  2. //根据点的定义,写出线段和三角形的定义,并通过主程序进行验证
  3. //mypoint.h
  4. class myPoint
  5. {
  6. public:
  7. myPoint();
  8. myPoint(double x, double y);
  9. double getX();
  10. double getY();
  11. private:
  12. double mX,mY;
  13. };
  14. #include <iostream> // 用于cout, cin, endl
  15. #include <cmath> // 用于pow, sqrt
  16. using namespace std;
  17. // Line类的声明
  18. class Line {
  19. private:
  20. myPoint p1, p2;
  21. public:
  22. Line(myPoint a, myPoint b) : p1(a), p2(b) {}
  23. double GetDistance() {
  24. return sqrt(pow(p2.getX() - p1.getX(), 2) + pow(p2.getY() - p1.getY(), 2));
  25. }
  26. };
  27. // Triangle类的声明
  28. class Triangle {
  29. private:
  30. myPoint p1, p2, p3;
  31. Line l1, l2, l3;
  32. public:
  33. Triangle(myPoint a, myPoint b, myPoint c) : p1(a), p2(b), p3(c), l1(a, b), l2(a, c), l3(b, c) {}
  34. double getGirth() {
  35. return l1.GetDistance() + l2.GetDistance() + l3.GetDistance();
  36. }
  37. double getArea() {
  38. double s = getGirth() / 2;
  39. return sqrt(s * (s - l1.GetDistance()) * (s - l2.GetDistance()) * (s - l3.GetDistance()));
  40. }
  41. };
  42. // myPoint类的实现
  43. myPoint::myPoint() : mX(0), mY(0) {}
  44. myPoint::myPoint(double x, double y) : mX(x), mY(y) {}
  45. double myPoint::getX() { return mX; }
  46. double myPoint::getY() { return mY; }
  47. int main()
  48. {
  49. double x1, x2, x3, y1, y2, y3;
  50. cout << "请输入点1的x的值:";
  51. cin >> x1;
  52. cout << "请输入点1的y的值:";
  53. cin >> y1;
  54. cout << "请输入点2的x的值:";
  55. cin >> x2;
  56. cout << "请输入点2的y的值:";
  57. cin >> y2;
  58. cout << "请输入点3的x的值:";
  59. cin >> x3;
  60. cout << "请输入点3的y的值:";
  61. cin >> y3;
  62. cout << "点1的坐标为:(" << x1 << "," << y1 << ")" << endl;
  63. cout << "点2的坐标为:(" << x2 << "," << y2 << ")" << endl;
  64. cout << "点3的坐标为:(" << x3 << "," << y3 << ")" << endl;
  65. myPoint p1(x1, y1), p2(x2, y2), p3(x3, y3);
  66. Line line1(p1,p2),line2(p1,p3),line3(p2,p3);
  67. cout<<"边长1的长度:"<<line1.GetDistance()<<endl;
  68. cout<<"边长2的长度:"<<line2.GetDistance()<<endl;
  69. cout<<"边长3的长度:"<<line3.GetDistance()<<endl;
  70. Triangle t(p1, p2, p3);
  71. cout << "该三角形的周长为:" << t.getGirth() << endl;
  72. cout << "该三角形的面积为:" << t.getArea() << endl;
  73. return 0;
  74. }