# Answer to Question #45593 in MatLAB | Mathematica | MathCAD | Maple for Deepika C

Question #45593

Write a single program that calculates the arithmetic mean (average), rms average, geometric mean

and harmonic mean for a set of n positive numbers. Your program should take two values xlow and

xhigh and generate 10000 random numbers in the range [xlow...xhigh], and should print out arithmetic

mean (average), rms average, geometric mean and harmonic mean.

and harmonic mean for a set of n positive numbers. Your program should take two values xlow and

xhigh and generate 10000 random numbers in the range [xlow...xhigh], and should print out arithmetic

mean (average), rms average, geometric mean and harmonic mean.

Expert's answer

`#include <cmath>`

#include <iostream>

#include <set>

#include <cstdlib>

#include <ctime>

#include <climits>

void generate1000Rand(std::set<int>* numbers, int xlow, int xhigh) {

for (int i = 0; i < 100; i++) {

numbers->insert(xlow + rand() % (xhigh + 1));

}

}

long double average(std::set<int>* numbers) {

long long unsigned sum = 0;

for ( std::set<int>::iterator it = numbers->begin(); it != numbers->end() ; it++ ) {

sum += *it;

}

return sum / 1000;

}

double rms( std::set<int>* numbers ) {

long long unsigned sum = 0;

for ( std::set<int>::iterator it = numbers->begin(); it != numbers->end() ; it++ ) {

sum += pow((*it), 2);

}

return sqrt(0.001*(sum));

}

long double geometricMean(std::set<int>* numbers) {

long long unsigned product = 1;

for ( std::set<int>::iterator it = numbers->begin(); it != numbers->end() ; it++ ) {

product *= *it;

}

return pow(product, 0.001);

}

long double harmonicMean( std::set<int>* numbers ) {

long double sum = 1;

for ( std::set<int>::iterator it = numbers->begin(); it != numbers->end() ; it++ ) {

sum += (long double)1/(*it);

}

return 1000/sum;

}

int main() {

srand(time(NULL));

std::set<int>* numbers = new std::set<int>();

int xlow, xhigh;

std::cout << "Please input lower and upper limit." << std::endl;

std::cin >> xlow >> xhigh;

if ( xlow > xhigh ) {

std::cout << "Wrong input. Lower limit got to be smaller than upper "<< std::endl;

return 0;

}

generate1000Rand(numbers, xlow, xhigh);

std::cout << "RMS: " << rms(numbers) << std::endl;

std::cout << "Average: " << average(numbers) << std::endl;

std::cout << "Geometric Mean: " << geometricMean(numbers) << std::endl;

std::cout << "Harmonic Mean: " << harmonicMean(numbers) << std::endl;

return 0;

}

## Comments

## Leave a comment