How to calculate the average value of float array in C++

2 Answers

0 votes
#include <iostream>

int main(void)
{
	float arr[5] = { 3.14, 2.2, 9.7, 1.17, 5.55 }, sum = 0.0;
	int size = (sizeof(arr) / sizeof(*arr));

	for (int i = 0; i < size; i++)
		sum += arr[i];

	float average = sum / size;
	std::cout << "Average = " << average << std::endl;

	return(0);
}



/*
run:

Average = 4.352

*/

 



answered Jun 12, 2017 by avibootz
edited Jun 12, 2017 by avibootz
0 votes
#include <iostream>
#include <array>

int main(void)
{
	std::array<float, 5> arr = { 3.14, 2.2, 9.7, 1.17, 5.55 };
	float sum = 0.0;

	for (int i = 0; i < arr.size(); i++)
		sum += arr[i];

	float average = sum / arr.size();
	std::cout << "Average = " << average << std::endl;

	return(0);
}



/*
run:

Average = 4.352

*/

 



answered Jun 12, 2017 by avibootz

Related questions

...