Bài tập C++ OOP: nạp chồng phương thức | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create an ArrayCalculator class in the file ArrayCalculator.cpp with the following information:

Explanation:

  • ArrayCalculator is a class without attributes.
  • maxOfArray(arr: int[], n: int) and maxOfArray(arr: double[], n: int) are two overloading static methods, they return the largest value in array arr.
  • minOfArray(arr: int[], n: int) and minOfArray(arr: double[], n: int) are two overloading static methods, they return the smallest value in array arr.

A program to test the above ArrayCalculator class: 

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

using namespace std;

int main() {
	int arr1[] = { 3, 4, 2 };
	double arr2[] = { 1.3, 4.2, 6.7 };

	cout << ArrayCalculator::minOfArray(arr1, sizeof(arr1) / sizeof(int)) << endl;
	cout << ArrayCalculator::minOfArray(arr2, sizeof(arr2) / sizeof(double)) << endl;
	cout << ArrayCalculator::maxOfArray(arr1, sizeof(arr1) / sizeof(int)) << endl;
	cout << ArrayCalculator::maxOfArray(arr2, sizeof(arr2) / sizeof(double)) << endl;
	return 0;
}

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

2
1.3
4
6.7

Instruction

Code sample:

class ArrayCalculator {
public:
	static int maxOfArray(int arr[], int n) {
		int maxValue = arr[0];
		for (int i = 1; i < n; i++) {
			if (arr[i] > maxValue) {
				maxValue = arr[i];
			}
		}
		return maxValue;
	}

	static double maxOfArray(double arr[], int n) {
		double maxValue = arr[0];
		for (int i = 1; i < n; i++) {
			if (arr[i] > maxValue) {
				maxValue = arr[i];
			}
		}
		return maxValue;
	}

	static int minOfArray(int arr[], int n) {
		int minValue = arr[0];
		for (int i = 1; i < n; i++) {
			if (arr[i] < minValue) {
				minValue = arr[i];
			}
		}
		return minValue;
	}

	static double minOfArray(double arr[], int n) {
		double minValue = arr[0];
		for (int i = 1; i < n; i++) {
			if (arr[i] < minValue) {
				minValue = arr[i];
			}
		}
		return minValue;
	}
};