经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
C++重载运算符实现分数加减乘除
来源:jb51  时间:2021/6/28 10:57:27  对本文有异议

本文实例为大家分享了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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接: NPS