【C++】实现一个有理数类
有理数:指所有可以用两个整数的商来表示的数
Rational.h
Rational类的接口
#ifndef _RATIONAL_H
#define _RATIONAL_H
#include <iostream>
#include <string>
class Rational {
public:
Rational();
Rational(int n);
Rational(int x, int y);
std::string toString();
friend Rational operator+(Rational r1, Rational r2);
friend Rational operator-(Rational r1, Rational r2);
friend Rational operator*(Rational r1, Rational r2);
friend Rational operator/(Rational r1, Rational r2);
private:
int num; // 分子
int den; // 分母
};
std::ostream &operator<<(std::ostream & os, Rational rat);
Rational operator+(Rational r1, Rational r2);
Rational operator-(Rational r1, Rational r2);
Rational operator*(Rational r1, Rational r2);
Rational operator/(Rational r1, Rational r2);
#endif //LEETCODE_RATIONAL_H
Rational.cpp
Rational类的实现
//
// Created by NFYD on 10/6/2022.
//
#include "rational.h"
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int gcd(int x, int y);
Rational::Rational() {
num = 0;
den = 1;
}
Rational::Rational(int n) {
num = n;
den = 1;
}
Rational::Rational(int x, int y) {
if (y == 0) printf("Rational: Division by zero!");
if (x == 0) {
num = 0;
den = 1;
} else {
int g = gcd(abs(x), abs(y));
num = x / g;
den = abs(y) / g;
if (y < 0) num = -num;
}
}
string Rational::toString() {
if (den == 1) {
return integerToString(num);
} else {
return integerTostring(num) + "/" + integrToString(den);
}
}
ostream & operator<<(ostream & os, Rational rat) {
return os << rat.toString();
}
Rational operator+(Rational r1, Rational r2) {
return Rational(r1.num * r2.den + r2.num * r1.den, r1 .den * r2.den);
}
Rational operator-(Rational r1, Rational r2) {
return Rational(r1.num * r2.den - r2.num * r1.den, r1 .den * r2.den);
}
Rational operator*(Rational r1, Rational r2) {
return Rational(r1.num * r2.num, r1.den * r2.den);
}
Rational operator/(Rational r1, Rational r2) {
return Rational(r1.num * r2.den, r1.den * r2.num);
}
int gcd(int x, int y) {
int r = x % y;
while (r != 0) {
x = y;
y = r;
r = x % y;
}
return y;
}
/* gcd也可以写成这种
int gcd(int a, int b) {
return b ? gcd(b, a % b) : a;
}
*/