C++重载运算符实现分数加减乘除
本文实例为大家分享了C++重载运算符实现分数加减乘除的具体代码,供大家参考,具体内容如下
实现结果如下图所示:
代码如下所示:
#include <iostream>
using namespace std;
class Rational {
public:
Rational operator+(Rational rhs);
Rational operator-(Rational rhs);
Rational operator*(Rational rhs);
Rational operator/(Rational rhs);
Rational(int num, int denom);
private:
void normalize(); //负责对分数做化简工作
int numerator;//分子
int denominator;//分母
friend std::ostream& operator<<(ostream& os, Rational f);
};
Rational::Rational(int num, int denom) {
numerator = num;
denominator = denom;
normalize();
}
//只允许分子为负数,若分母为负数则把负数挪到分子部分
//利用欧几里得算法将分数简化
void Rational::normalize() {
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
//欧几里得算法
int a = abs(numerator);
int b = abs(denominator);
//求出最大公约数,a
//eg: a=12,b=9.
//t=3 a=9 b=3
//t=0 a=3 b=0
while (b > 0) {
int t = a % b;//t为余数
a = b; //a取除数
b = t; //b取余数
}
//分子、分母分别处以最大公约数
numerator /= a;
denominator /= a;
}
//重载运算符函数是类的成员函数
//分数是先通分再加减
// a*d+b*c / b*d
Rational Rational::operator+(Rational rhs) {
int a = numerator;
int b = denominator;
int c = rhs.numerator;
int d = rhs.denominator;
return Rational(a*d+b*c,b*d);
}
Rational Rational::operator-(Rational rhs) {
int a = numerator;
int b = denominator;
int c = rhs.numerator;
int d = rhs.denominator;
return Rational(a*d - b*c, b*d);
/*
**这里有个偷懒的写法
rhs.numerator = -rhs.numerator;
return operator+(rhs);
*/
}
Rational Rational::operator*(Rational rhs) {
int a = numerator;
int b = denominator;
int c = rhs.numerator;
int d = rhs.denominator;
return Rational(a*c, b*d);
}
Rational Rational::operator/(Rational rhs) {
int t = rhs.denominator;
rhs.denominator = rhs.numerator;
rhs.numerator = t;
return operator*(rhs);
}
//该函数是友元函数,因此不用加空间域名
ostream& operator<<(ostream& os, Rational f);
int main() {
Rational r1(4, 18);
Rational r2(14, 18);
cout << r1 << " + " << r2 << " = " << (r1 + r2) << endl;
cout << r1 << " - " << r2 << " = " << (r1 - r2) << endl;
cout << r1 << " * " << r2 << " = " << (r1 * r2) << endl;
cout << r1 << " / " << r2 << " = " << (r1 / r2) << endl;
system("pause");
return 0;
}
ostream& operator<<(ostream& os, Rational f) {
os << f.numerator << "/" << f.denominator;
return os;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
以上是 C++重载运算符实现分数加减乘除 的全部内容, 来源链接: utcz.com/p/246338.html