The C++ Function to Compute the Average of Numbers


The C is the subset of C++ and hence many C programmers that come from embedded background claim they can write proper C++ code. So here is a task (could be a C++ coding homework) that can easily distinguish the C programmers and the modern C++ programmers.

You are given a task to write a function that computes the average for a few numbers. The C way (textbook example) would be:

double GetAverage(double *numbers, int length) {
   double sum = 0.0;
   for (int i = 0; i < length; ++ i) sum += numbers[i];
   return sum / length;
}

With modern C++ features, you can use std::vector to replace teh error-prone array pointers and use the std::accumulate to apply a reduce-like function to sum up all values.

double GetAverage(std::vector<double> numbers)
{
	return (double)std::accumulate(numbers.begin(), numbers.end(), 0, 
		[](const auto &a, const auto &b) { 
		  return a + b; 
		}
	) / numbers.size();
}

The above also uses a inline anoymous function delegate that is passed as a parameter. And also the “auto” keyword is modern C++ as well. Also, write some unit tests to test your functions shows your modern development skills:

#include "stdafx.h"
#include "CppUnitTest.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace AverageUtils
{		
	TEST_CLASS(AverageTests)
	{
	public:
		
		TEST_METHOD(Test_AverageWithFourNumbers)
		{
			Question1 obj;
			Assert::AreEqual(2.5, obj.GetAverage({ 1, 2, 3, 4 }));
		}

		TEST_METHOD(Test_AverageWithOnlyOneNumber) // test 1 element
		{
			Question1 obj;
			Assert::AreEqual(5.0, obj.GetAverage({ 5 }));
		}

	};
}

–EOF (The Ultimate Computing & Technology Blog) —

281 words
Last Post: How to Transform the Values in Excel Files to a Column of Values?
Next Post: How to Design/Implement a Queue using Two Stacks?

The Permanent URL is: The C++ Function to Compute the Average of Numbers (AMP Version)

One Response

Leave a Reply