宋桂琴白皮书项目2(P8)二、1
题目:
编写有理数(即分数,包括整数类型的分子,分母)类,并进行运算符重载,编写运算符“+”,“-”,“*”,“/”的重载函数,在主函数的函数体内实现使用运算符重载直接进行有理数对象的加减乘除运算。
程序:(部分)
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
class Rational {
protected:
int denomenator;//分母
int molecule;//分子
public:
void input() {
cout << "please enter the molecule and the denomenator" << endl;
cin >> molecule >> denomenator;
}
void reduction();
public:
friend Rational operator +(Rational, Rational);
friend Rational operator *(Rational, Rational);
friend ostream& operator <<(ostream&, Rational&);
};
inline int gcd(int a, int b) {
int r;
while (b > 0) {
r = a % b;
a = b;
b = r;
}
return a;
}
ostream& operator <<(ostream& output, Rational& r) {
if(r.denomenator!=1){
output << r.molecule << "/" << r.denomenator;
}
else {
output << r.molecule;
}
return output;
}
void Rational::reduction() {//约分函数
int gcdred = gcd(denomenator, molecule);
denomenator /= gcdred;
molecule /= gcdred;
return;
}
Rational operator +(Rational r1, Rational r2) {//运算符加号的重载
Rational res;
int lcm_plus = r1.denomenator * r2.denomenator;
res.denomenator = lcm_plus;
res.molecule = ((lcm_plus / r1.denomenator) * r1.molecule) + ((lcm_plus / r2.denomenator) * r2.molecule);
res.reduction();
return res;
}
Rational operator *(Rational r1, Rational r2) {
Rational res;
res.denomenator = r1.denomenator * r2.denomenator;
res.molecule = r1.molecule * r2.molecule;
res.reduction();
return res;
}
int main() {
Rational a, b, res;
a.input();
b.input();
res = a + b;
cout << a << "+" << b << "=" << res<<endl;
res = a * b;
cout << a << "*" << b << "=" << res << endl;
}