Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
#include <cmath> // for std::pow
#include <vector>
class mean{
public:
mean(){};
virtual ~mean(){};
virtual mean & add_data(int d) = 0;
virtual double get_mean() const =0;
virtual void print(std::ostream & o=std::cout) const =0;
private:
mean(const mean & a) = default;
mean & operator=(const mean & a) = default;
};
class arithmetic:public mean{
public:
arithmetic(): ncount_{0}, rsum_{0}, amean_{0} {};
// Use Relaxation return type, the covariant rule
arithmetic & add_data(int d) override { *this+=d; return *this; }
arithmetic & operator+=(int d){
rsum_+=d;
ncount_++;
double stemp=static_cast<double>(rsum_);
double ntemp=static_cast<double>(ncount_);
amean_=stemp/ntemp;
return *this;
}
double get_mean() const override { return amean_;}
void print(std::ostream &o) const override {
std::cout << " Arithmetic mean: " << get_mean() << std::endl;
}
private:
int ncount_;
int rsum_;
double amean_;
};
class geometric:public mean{
public:
geometric(): ncount_{0}, rproduct_{1}, gmean_{0} {};
// Use Relaxation return type, the covariant rule
geometric & add_data(int d){ *this*=d; return *this; }
geometric & operator*=(int d){
rproduct_*=d;
ncount_++;
double ptemp=static_cast<double>(rproduct_);
double ntemp=static_cast<double>(ncount_);
gmean_=std::pow(ptemp,1.0/ntemp);
return *this;
}
double get_mean() const { return gmean_;}
void print(std::ostream &o) const override {
std::cout << " Geometrical mean: " << get_mean() << std::endl;
}
private:
int ncount_;
int rproduct_;
double gmean_;
};
int main(){
arithmetic a;
geometric b;
std::vector<mean*> means;
means.push_back(&a);
means.push_back(&b);
int indata{0};
std::cout <<"Enter values [Ctrl-D to finish]: " <<std::endl;
while(std::cin>>indata){
// a+=indata;
// b*=indata;
for(auto i: means) i->add_data(indata);
}
for(const auto i: means) i->print();// for(std::vector<mean*>::const_iterator i=means.begin(); i!= means.end(); ++i) (*i)->print();
return 0;
}