Sheet0, Exercise 1

This commit is contained in:
Lisa Pizzo 2025-10-16 15:31:00 +02:00
commit 61675ba36d

85
mainEx1.cpp Normal file
View file

@ -0,0 +1,85 @@
#include <iostream> // for input/output
#include <cmath> // for pow (used in geometric mean)
#include <vector>
using namespace std;
void computeMeans(int a, int b, int c, double &arith, double &geom, double &harm) { //doesn't return anything
arith = (a + b + c) / 3.0;
geom = pow(a * b * c, 1.0 / 3.0);
harm = 3.0 / ( (1.0 / a) + (1.0 / b) + (1.0 / c) );
}
void computeMeansVector(const vector<int> &v, double &arith, double &geom, double &harm) {
int n = v.size(); // number of elements in the vector
// If the vector is empty, avoid division by zero
if (n == 0) {
arith = geom = harm = 0.0;
return;
}
double sum = 0.0;
double product = 1.0;
double reciprocalSum = 0.0;
for (int i = 0; i < n; ++i) {
sum += v[i];
product *= v[i];
reciprocalSum += 1.0 / v[i];
}
arith = sum / n;
geom = pow(product, 1.0 / n);
harm = n / reciprocalSum;
}
int main() {
int x, y, z;
double am, gm, hm; // to store the results
double amV, gmV, hmV; // to store the results vector case
vector<int> values;
// Example input 1
x = 1; y = 4; z = 16;
computeMeans(x, y, z, am, gm, hm);
cout << "Input: (1, 4, 16)" << endl;
cout << "Arithmetic mean: " << am << endl;
cout << "Geometric mean: " << gm << endl;
cout << "Harmonic mean: " << hm << endl << endl;
values = {1, 4, 16};
computeMeansVector(values, amV, gmV, hmV);
cout << "Input: (1, 4, 16)" << endl;
cout << "Arithmetic mean: " << amV << endl;
cout << "Geometric mean: " << gmV << endl;
cout << "Harmonic mean: " << hmV << endl << endl;
// Example input 2
x = 2; y = 3; z = 5;
computeMeans(x, y, z, am, gm, hm);
cout << "Input: (2, 3, 5)" << endl;
cout << "Arithmetic mean: " << am << endl;
cout << "Geometric mean: " << gm << endl;
cout << "Harmonic mean: " << hm << endl << endl;
values = {2, 3, 5};
computeMeansVector(values, amV, gmV, hmV);
cout << "Input: (2, 3, 5)" << endl;
cout << "Arithmetic mean: " << amV << endl;
cout << "Geometric mean: " << gmV << endl;
cout << "Harmonic mean: " << hmV << endl << endl;
// Example input 3
x = 1000; y = 4000; z = 16000;
computeMeans(x, y, z, am, gm, hm);
cout << "Input: (1000, 4000, 16000)" << endl;
cout << "Arithmetic mean: " << am << endl;
cout << "Geometric mean: " << gm << endl;
cout << "Harmonic mean: " << hm << endl << endl;
values = {1000, 4000, 16000};
computeMeansVector(values, amV, gmV, hmV);
cout << "Input: (1000, 4000, 16000)" << endl;
cout << "Arithmetic mean: " << amV << endl;
cout << "Geometric mean: " << gmV << endl;
cout << "Harmonic mean: " << hmV << endl << endl;
return 0;
}