1.头文件
2.源文件
1.CRation.h
- #pragma once
-
- class CRation {
- int n;//分子
- int d;//分母
- int Gcd();//求最大公约数
- public:
- CRation(int n, int d); //构造
- CRation *Add(CRation &r); // 加法
- CRation *Multiple(CRation &r); //乘法
- CRation *Subtract(CRation &r); //减法
- int GetN();
- int GetD(); // 输出
-
- };
2.CRation.cpp
- #include<math.h>
- #include"CRation.h"
-
- CRation::CRation(int n0, int d0)
- {
- n = n0;
- d = d0;
- int x = Gcd();
- n = n / x;
- d = d / x;
- }
-
- int CRation::Gcd() {//辗转相除法
- int x = abs(n), y = abs(d), t;
- if (x > y) {
- t = x, x = y, y = t;//交换x和y
- }
- while(y%x!=0){
- t = y % x;
- y = x;
- x = t;
- }
- return x;
- }
-
- int CRation::GetN() {
- return n;
- }
-
- int CRation::GetD() {
- return d;
- }
-
- CRation *CRation::Add(CRation &r) {
- int d1 = d * r.d; //分母乘积
- int n1 = n * r.d + r.n*d;//分子相加
- CRation *q = new CRation(n1, d1);//未约分的分数
- return q;
- }
-
- CRation *CRation::Multiple(CRation &r) {
- int d2 = d * r.d;
- int n2 = n * r.n;
- CRation *q = new CRation(n2, d2);
- return q;
- }
-
- CRation *CRation::Subtract(CRation &r) {
- int d1 = d * r.d; //分母乘积
- int n1 = n * r.d - r.n*d;//分子相加
- CRation *q = new CRation(n1, d1);//未约分的分数
- return q;
- }
3.main.cpp
- #include<iostream>
- #include"CRation.h"
- using namespace std;
-
- int main() {
- CRation r1(5, 8);
- CRation r2(18, 27);
- //加法
- CRation *p1 = r1.Add(r2);
- cout << p1->GetN() << "/" << p1->GetD() << endl;
- //乘法
- CRation *p2 = r1.Multiple(r2);
- cout << p2->GetN() << "/" << p2->GetD() << endl;
- //减法
- CRation *p3 = r1.Subtract(r2);
- cout << p3->GetN() << "/" << p3->GetD() << endl;
- //计算7/19 * 4/5 - 3/8
- CRation r3(7, 19);
- CRation r4(4, 5);
- CRation r5(3, 8);
- CRation *p4 = r3.Multiple(r4);
- CRation *p5 = (*p4).Subtract(r5);
- cout <<"7/19 * 4/5 - 3/8 = "<< p5->GetN() << "/" << p5->GetD() << endl;
- getchar();
- return 0;
- }
1.函数Gcd()是辗转相除法求最大公约数
2.注意CRation里加减乘的返回值是CRation指针
3.注意自己写的头文件用双引号""括起来而不是<>