"Protoman" <> wrote in message
news: oups.com...
> Hey, is this program right? It calculates the average, harmonic mean,
> quadratic mean, and the standard deviation for two numbers. Can you
> proofread it for me?
> Here it is:
>
> #include <iostream>
> #include <cstdlib>
> #include <cmath>
> using namespace std;
>
> template <class T>
> class avg
> {
> public:
> T operator()(const T& num, const T& num2)const
> {
> T ret=((num+num2)/2);
> return ret;
> }
> T operator()(const T& num, const T& num2, int x)const
> {
> T ret=(sqrt(pow(num,2)+pow(num,2)));
> return ret;
> }
> T operator()(const T& num, const T& num2,int x,int y)const
> {
> T ret=(2/(1/num+1/num2));
> return ret;
> }
> operator T()const{return static_cast<T>(value);}
> private:
> T value;
> };
>
> template <class T>
> class Stat
> {
> public:
> T operator()(T avg,const T& num,const T& num2)const
> {
> T ret=num-avg;
> T ret2=num2-avg;
> T ret3=(pow(ret,2)+pow(ret2,2)/2);
> T ret4=sqrt(ret3);
> return ret4;
> }
> operator T()const{return static_cast<T>(value);}
> private:
> T value;
> };
>
> int main()
> {
> for(;
> {
> long double num;
> long double num2;
> avg<long double> Avg;
> Stat<long double> StdDev;
> cout << "Enter two numbers: " << endl;
> cin >> num >> num2;
> cout << "Here's the average: " << fixed << Avg(num,num2) << endl;
> cout << "Here's the quadratic mean: " << fixed << Avg(num,num2,0) <<
> endl;
> cout << "Here's the harmonic mean: " << fixed << Avg(num,num2,0,0) <<
> endl;
> cout << "Here's the standard deviation: " << fixed <<
> StdDev(Avg(num,num2),num,num2)
> << endl;
> }
> system ("PAUSE");
> return 0;
> }
>
> Also, is there anyway I can make it so StdDev can use Avg's arguments
> so I don't need StdDev to have copies of Avg's arguments? And is there
> anyway I can make Avg and StdDev have variable numbers of paramaters; I
> don't want to recompile everytime I want to do more (or less) numbers?
> Thanks a lot.
>
You can use classes to make your statistic work with any number of samples.
For instance (unchecked):
class sample_mean
{
private:
unsigned m_count; // number of samples
double m_sum_x1; // sum of samples
public:
sample_mean() : m_count(0), m_sum_x1(0.0) {}
unsigned n() const {return m_count;}
double xbar() const // no check for 0 samples
{
return m_sum_x1 / m_count;
}
template <typename T>
sample_mean &operator () (T x)
{
++m_count;
m_sum_x1 += static_cast<double>(x);
return *this;
}
void clear()
{
m_count = 0;
m_sum_x1 = 0.0;
}
};
You use it like this:
sample_mean m;
m(1.2)(3.6)(-0.4);
std::cout << m.xbar() << '\n';
--
Cycho{HHR}
http://home.rochester.rr.com/cyhome/