您的位置:首页 > 娱乐 > 明星 > 面向对象程序设计:运算符重载习题

面向对象程序设计:运算符重载习题

2024/10/6 22:23:06 来源:https://blog.csdn.net/weixin_45080800/article/details/139786077  浏览:    关键词:面向对象程序设计:运算符重载习题

宋桂琴白皮书项目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;}

运行:(部分)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com