// implementazione della classe fraction #include #include #include "fraction.h" // includo l'interfaccia using namespace std; // 3 costruttori fraction::fraction() { this->n = this->d = 1; } fraction::fraction(int a) { this->n=a; this->d=1; } fraction::fraction(int a, int b) { if (b==0) { cout << "Error: division by zero! " << "... fraction now is equal to 1 \n\n"; this->n = this->d = 1; } else { this->n = a; this->d = b; this->reduce(); } } // test di positivit� bool fraction::is_pos(){ return (this->n > 0); } // operazioni di lettura int fraction::get_numerator() { return this->n; } int fraction::get_denumerator() { return this->d; } // operazioni di scrittura void fraction::set_numerator(int a) { this->n=a; this->reduce(); } void fraction::set_denumerator(int a) { if (a==0) { cout << "Error: divisione by zero! " << "Fraction not modified! \n"; return; } this->d = a; this->reduce(); } // operazioni aritmetiche fraction fraction::sum(const fraction & f) { fraction tmp; tmp.n = this->n * f.d + this->d * f.n; tmp.d = this->d * f.d; tmp.reduce(); return tmp; } fraction fraction::sub(const fraction & f) { fraction tmp; tmp.n = this->n * f.d - this->d * f.n; tmp.d = this->d * f.d; tmp.reduce(); return tmp; } fraction fraction::mul(const fraction & f) { fraction tmp; tmp.n = this->n * f.n; tmp.d = this->d * f.d; tmp.reduce(); return tmp; } fraction fraction::div( const fraction & f) { if (f.n==0) { cout << "Error: division by zero! " << "Return 1 by default \n\n"; fraction x; return x; } fraction tmp(f.d,f.n); return this->mul(tmp); } // operazione di stampa void fraction::print() { cout << this->n << "/" << this->d; } //--------------------------------------------------- // funzione di utilit� //--------------------------------------------------- void fraction::reduce() { if ( this->n == 0 ) { // frazione uguale a zero this->d=1; return; } if ( this->d < 0 ) { // rendo il denominatore positivo this->n *= -1; this->d *= -1; } int nn=abs(this->n), dd=abs(this->d); while ( nn != dd ) { if ( nn > dd ) nn -= dd; else dd -= nn; } this->n /= nn; this->d /= nn; }