這是學寫C++物件與類別的第一個程式,
還在摸索中...
------
Rational.h
#include <iostream>
using namespace std;
class Rational {
public:
Rational(int num=0, int den=1); //constructor
//儲存分數( C++ 不提供分數(如 1/3, 4/7)的資料型態)
//定義運算子
Rational operator + (const Rational & r);
Rational operator - (const Rational & r);
Rational operator * (const Rational & r);
Rational operator / (const Rational & r);
void print(string s);//宣告函式,寫在下面 void Rational::print(string s)
private:
int _num;
int _den;
int ans;
int gcd(int x, int y);//宣告最大公因數的函式
int _gcd;//存最大公因數
int lcm;//最小公倍數
};
</iostream>
Rational.cpp
#include "Rational.h"
using namespace std;
Rational::Rational(int num, int den) {
_num = num;
_den = den;
}
int Rational::gcd(int x,int y){
if(x%y!=0) return gcd(y, x%y);
else return y;
}
Rational Rational::operator + (const Rational & r) {
_gcd = gcd(_den,r._den);
lcm = (_den * r._den) / _gcd;
Rational z(_num * (r._den/_gcd) + r._num * (_den/_gcd),lcm);
return z;
}
Rational Rational::operator - (const Rational & r) {
_gcd = gcd(_den,r._den);
lcm = (_den * r._den) / _gcd;
Rational z(_num * (r._den/_gcd) - r._num * (_den/_gcd),lcm);
return z;
}
Rational Rational::operator * (const Rational & r) {
_gcd = gcd(_num * r._num , _den * r._den);
if(_gcd!=1){
Rational z(_num * r._num / _gcd, _den * r._den / _gcd);
return z;
}
else{
Rational z(_num * r._num , _den * r._den);
return z;
}
}
Rational Rational::operator / (const Rational & r) {
_gcd = gcd(_num * r._den , _den * r._num);
if(_gcd!=1){
Rational z(_num * r._den / _gcd, _den * r._num / _gcd);
return z;
}
else{
Rational z(_num * r._den , _den * r._num);
return z;
}
}
void Rational::print(string s){
cout << s <<":" << _num <<"/"<<_den<<endl;
}
main.cpp
#include "Rational.h"
using namespace std;
int main() {
Rational a(1,2);
Rational b(3,4);
Rational c, d, e, f;
c = a + b;
d = a - b;
e = a * b;
f = a / b;
a.print("a");
b.print("b");
c.print("a+b");
d.print("a-b");
e.print("a*b");
f.print("a/b");
return 0;
}
執行結果如下: