Bài tập C++ OOP: cài đặt lớp Math | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create a Math class within math.cpp file with the following information:

In the class diagram, the underlined methods and properties are the static methods and static properties.

In the Math class:

  • PI is the static whose default value is 3.14
  • abs(x: int) is the function that returns the absolute value of x.
  • add(x: int, y: int) is the function that returns the sum of x and y.
  • subtract(x: int, y: int) is the function that returns the difference of x and y.
  • min(x: int, y: int) is the function that returns the smaller of two numbers.
  • max(x: int, y: int) is the function that returns the bigger of two numbers.
  • pow(x: int, y: int) is the function that returns the result of xy.

A program to test Math class:

#include <iostream> 
#include "math.cpp"

using namespace std;

int main() {
	cout << Math::abs(-2) << endl;
	cout << Math::add(2, 3) << endl;
	cout << Math::subtract(2, 3) << endl;
	cout << Math::min(2, 3) << endl;
	cout << Math::max(2, 3) << endl;
	cout << Math::pow(2, 3) << endl;
	return 0;
}

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

2
5
-1
2
3
8

Instruction

Code sample:

class Math {
public:
	static int abs(int x) {
		return x < 0 ? -x : x;
	}

	static int add(int x, int y) {
		return x + y;
	}

	static int subtract(int x, int y) {
		return x - y;
	}

	static int min(int x, int y) {
		return x < y ? x : y;
	}

	static int max(int x, int y) {
		return x > y ? x : y;
	}

	static int pow(int x, int y) {
		int power = 1;
		for (int i = 0; i < y; i++) {
			power *= x;
		}
		return power;
	}
};