# 我是c++初學者..請問要如何設計一個有裡數 謝謝你們

Create a class Rational number (fractions) WITH THE FOLLOWING CAPABILITIES:

A.Create a constructor that prevents a 0 denominator in a fraction, reduces or simplifies fractions that are not in reduced form and avoids negative denominators.

C.Overload the relational and equality operators for this class.

Rating
• pfg
Lv 4

#include <iostream>

using namespace std;

class Rational {

public:

Rational(int num = 0, int den = 1); //A

Rational operator+(const Rational &v) //B

{ return Rational(m_num*v.m_den + m_den*v.m_num, m_den*v.m_den); }

Rational operator-(const Rational &v) //B

{ return Rational(m_num*v.m_den - m_den*v.m_num, m_den*v.m_den); }

Rational operator*(const Rational &v) //B

{ return Rational(m_num*v.m_num, m_den*v.m_den); }

Rational operator/(const Rational &v) //B

{ return Rational(m_num*v.m_den, m_den*v.m_num); }

bool operator>(const Rational &v) //C

{ return (m_num*v.m_den) > (m_den*v.m_num); }

bool operator<(const Rational &v) //C

{ return (m_num*v.m_den) < (m_den*v.m_num); }

bool operator==(const Rational &v) //C

{ return (m_num*v.m_den) == (m_den*v.m_num); }

bool operator>=(const Rational &v) //C

{ return !(*this < v); }

bool operator<=(const Rational &v) //C

{ return !(*this > v); }

bool operator!=(const Rational &v) //C

{ return !(*this == v); }

void print() { cout << m_num << "/" << m_den; }

private:

int m_num;

int m_den;

void reduce(); //A

};

Rational::Rational(int num, int den)

{

if (!den)

den = 1;

else if (den<0) {

num = -num;

den = -den;

}

m_num = num;

m_den = den;

reduce();

}

void Rational::reduce()

{

int a, b;

if (!m_num) {

m_den = 1;

return;

}

if (m_den > m_num) { a = m_den; b = m_num; }

else { a = m_num; b = m_den; }

while (1) {

int t;

t = a % b;

if (t==1)

return;

else if (!t)

break;

a = b;

b = t;

}

m_den /= b;

m_num /= b;

}

int _tmain(int argc, _TCHAR* argv[])

{

Rational a = Rational(4, 6);

Rational b = Rational(4, 12);

Rational c;

c = a+b; a.print(); cout<< " + "; b.print(); cout<< " = "; c.print(); cout<< endl;

c = a-b; a.print(); cout<< " - "; b.print(); cout<< " = "; c.print(); cout<< endl;

c = a*b; a.print(); cout<< " * "; b.print(); cout<< " = "; c.print(); cout<< endl;

c = a/b; a.print(); cout<< " / "; b.print(); cout<< " = "; c.print(); cout<< endl;

if (a > b) { a.print(); cout<< " > "; b.print(); cout<< endl; }

if (a < b) { a.print(); cout<< " < "; b.print(); cout<< endl; }

if (a == b) { a.print(); cout<< " == "; b.print(); cout<< endl; }

if (a >= b) { a.print(); cout<< " >= "; b.print(); cout<< endl; }

if (a <= b) { a.print(); cout<< " <= "; b.print(); cout<< endl; }

if (a != b) { a.print(); cout<< " != "; b.print(); cout<< endl; }

return 0;

}

Source(s): self