我是靠谱客的博主 朴素茉莉,最近开发中收集的这篇文章主要介绍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++重载运算符实现分数加减乘除的全部内容,希望文章能够帮你解决C++重载运算符实现分数加减乘除所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(89)

评论列表共有 0 条评论

立即
投稿
返回
顶部