Bài tập C++ OOP: điểm và hình tam giác | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create a Point class in Point.cpp file and a Triangle class in Triangle.cpp file like the following class diagram:

  

Explanation:

Point class

  • This is the class used to store information about a point in a two-dimensional coordinate system.
  • x and y attributes are abscissa and coordinate respectively.
  • Point(x: int, y: int) is the parameterized constructor which is used for initializing values to x and y.
  • setX(), getX(), setY(), getY() are setters and getters.

Triangle class

  • This is the class that stores information about triangles.
  • vertice1, vertice2, vertice3 attributes describe 3 vertices of the triangle.
  • Triangle(vertice1: Point, vertice2: Point, vertice3: Point) is the parameterized constructor which is used for initializing values to 3 vertices of the triangle.
  • Triangle(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) is the parameterized constructor which is used for initializing values to 3 vertices of the triangle.
  • getPerimeter() method returns the perimeter of a triangle. For example, if vertice1 = (1, 3), vertice2 = (2, 3), vertice3 = (4, 2), getPerimeter() method returns the following result 8.48528137423857.

A program to test Triangle class:

#include <iostream>
#include "Point.cpp"
#include "Triangle.cpp"

using namespace std;

int main() {
	Point vertice1(1, 3);
	Point vertice2(2, 3);
	Point vertice3(4, 2);
	Triangle triangle1(vertice1, vertice2, vertice3);
	Triangle triangle2(4, 5, 2, 6, 3, 7);
	cout << triangle1.getPerimeter() << endl;
	cout << triangle2.getPerimeter() << endl;
	return 0;
}

When the above code is compiled and executed, it produces the following result:

6.39835
5.88635

Note: Codelearn compiler accepts the numerical error less than 0.000001

Instruction

Code sample:

Point.cpp file

#pragma once

class Point {
private:
	int x;
	int y;

public:
	Point() {
		
	}

	Point(int x, int y) {
		this->x = x;
		this->y = y;
	}

	int getX() {
		return x;
	}

	void setX(int x) {
		this->x = x;
	}

	int getY() {
		return y;
	}

	void setY(int y) {
		this->y = y;
	}
};

Triangle.cpp file 

#include <math.h>
#include "Point.cpp"

class Triangle {
private:
	Point vertice1;
	Point vertice2;
	Point vertice3;

public:
	Triangle(Point vertice1, Point vertice2, Point vertice3) {
		this->vertice1 = vertice1;
		this->vertice2 = vertice2;
		this->vertice3 = vertice3;
	}
	
	Triangle(int x1, int y1, int x2, int y2, int x3, int y3) {
		vertice1 = Point(x1, y1);
		vertice2 = Point(x2, y2);
		vertice3 = Point(x3, y3);
	}

	double getPerimeter() {
		double d1 = sqrt(pow(vertice1.getX() - vertice2.getX(), 2)
			+ pow(vertice1.getY() - vertice2.getY(), 2));
		double d2 = sqrt(pow(vertice1.getX() - vertice3.getX(), 2)
			+ pow(vertice1.getY() - vertice3.getY(), 2));
		double d3 = sqrt(pow(vertice2.getX() - vertice3.getX(), 2)
			+ pow(vertice2.getY() - vertice3.getY(), 2));
		return d1 + d2 + d3;
	}
};