代码:
/* * 04737 c++ 自学考试2019版 第二章课后练习 * 程序设计题 2 * 需求:设计并实现二维坐标系下点的类Point.... */ #include <iostream> #include <string> #include <cmath> using namespace std; class Point { public: Point(); Point(double, double); void setPoint(double, double); double getDistance(); double getDistance(Point); void printPoint(); private: double x, y; }; Point::Point() { x = 0, y = 0; } Point::Point(double x0, double y0) { x = x0, y = y0; } void Point::setPoint(double x0, double y0) { x = y0, y = y0; return; } void Point::printPoint() { cout << "(" << x << "," << y << ")" << endl; return; } double Point::getDistance() { return sqrt(x * x + y * y); } //求两点之间的距离 double Point::getDistance(Point p) { return sqrt(pow(abs(x - p.x), 2) + pow(abs(y - p.y), 2)); //公式是勾股定理 sqrt()函数求开根号, pow(a,b)函数是a的b次方例如:pow(3,2)是3的平方~ } bool isTriangle(double a, double b, double c) { //三角形的组成条件为: 任意一边小于其他两边之和 if ((a < b + c) && (b < a + c) && (c < a + b)) { return true; } return false; } int main() { Point p(0, 0), p1(1, 2), p2(3, 4), p3(4, 6); cout << "有4个点:" << endl; cout << "p:"; p.printPoint(); cout << "p1:"; p1.printPoint(); cout << "p2:"; p2.printPoint(); cout << "p3:"; p3.printPoint(); // 给定点到原点的距离 cout << endl; double d1 = p1.getDistance(); double d2 = p2.getDistance(); double d3 = p3.getDistance(); cout << "点p1到原点p的距离:" << d1 << endl; cout << "点p2到原点p的距离:" << d2 << endl; cout << "点p3到原点p的距离:" << d3 << endl; // 给定两点间的距离 cout << endl; double a = p1.getDistance(p2); double b = p1.getDistance(p3); double c = p2.getDistance(p3); cout << "点p1到p2的距离:" << a << endl; cout << "点p1到p3的距离:" << b << endl; cout << "点p2到p3的距离:" << c << endl; // 判断给定3个点能够构成三角形 cout << endl; bool it = isTriangle(a, b, c); if (it) { cout << "点p1,p2,p3可以构成三角形"; } else { cout << "点p1,p2,p3不可以构成三角形"; } cout << endl; return 0; }
运行结果:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。