Bài tập nạp chồng phương thức trong 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.
  • sumOfArray(arr: int[], n: int) is a static method which is used to calculate the sum of elements in arr (n is the number of elements in arr)
  • sumOfArray(arr: double[], n: int) is a static method which is used to calculate the sum of elements in arr (n is the number of elements in 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::sumOfArray(arr1, sizeof(arr1) / sizeof(int)) << endl;
	cout << ArrayCalculator::sumOfArray(arr2, sizeof(arr2) / sizeof(double)) << endl;
	return 0;
}

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

9
12.2

Instruction

Code sample:

class ArrayCalculator {
public:
	static int sumOfArray(int arr[], int n) {
		int sum = 0;
		for (int i = 0; i < n; i++) {
			sum += arr[i];
		}
		return sum;
	}

	static double sumOfArray(double arr[], int n) {
		double sum = 0;
		for (int i = 0; i < n; i++) {
			sum += arr[i];
		}
		return sum;
	}
};