一.问题描述
定义一个分数类,包含分子、分母
实验要求:
- 含有无参的默认构造函数,并进行构造函数的重载;
- 重载分数的加法+、减法-、数乘*这三运算符;
- 重载分数的输入和输出运算符;
- 重载分数的关系运算符==,!=,>=,<=;
定义约简函数,使分子分母没有公因子。
二.设计思路
三.流程图
四.伪代码
1
五.代码实现
#include<iostream>
using namespace std;
class fraction {
private:
int zi, mu;
public:
fraction(){}
fraction(int a, int b) :zi(a), mu(b){}
~fraction(){}
void fractionReduction() {
int big, n = 1;
big = (zi > mu ? zi : mu);
for (int i = big; i >= 1; i--) {
if (zi % i == 0 && mu % i == 0) {
zi /= i; //分子(前项)
mu /= i; //分母(后项)
n *= i; //公约数
}
}
}
friend istream& operator >> (istream& in, fraction& a) {
in >> a.zi >> a.mu;
return in;
}
friend ostream& operator <<(ostream& out, fraction& a) {
out << a.zi << " / " << a.mu;
return out;
}
fraction operator+ (fraction& a) {
fraction res;
res.zi = zi * a.mu + a.zi * mu;
res.mu = mu * a.mu;
res.fractionReduction();
return res;
}
fraction operator- (fraction& a) {
fraction res;
res.zi = zi * a.mu - a.zi * mu;
res.mu = mu * a.mu;
res.fractionReduction();
return res;
}
friend fraction operator* (int num, fraction& a) {
fraction res;
res.mu = a.mu;
res.zi = num * a.zi;
res.fractionReduction();
return res;
}
friend int operator ==(fraction& a, fraction& b) {
a.fractionReduction();
b.fractionReduction();
if (a.zi == b.zi && a.mu == b.mu) return 1;
else return 0;
}
friend int operator !=(fraction& a, fraction& b) {
a.fractionReduction();
b.fractionReduction();
if (a.zi != b.zi && a.mu != b.mu) return 1;
else return 0;
}
friend int operator >=(fraction& a, fraction& b) {
a.fractionReduction();
b.fractionReduction();
if (a.zi >= b.zi && a.mu >= b.mu) return 1;
else return 0;
}
friend int operator <=(fraction& a, fraction& b) {
a.fractionReduction();
b.fractionReduction();
if (a.zi <= b.zi && a.mu <= b.mu) return 1;
else return 0;
}
};
int main() {
fraction a, b, c;
int s;
cin >> a >> b;
cin >> s;
c = a + b;
cout << c << endl;
c = a - b;
cout << c << endl;
c = s * b;
cout << c << endl;
if (a >= b) {
cout << "a>=b" << endl;
}
if (a <= b) {
cout << "a<=b" << endl;
}
if (a != b) {
cout << "a!=b" << endl;
}
if (a == b) {
cout << "a=b" << endl;
}
return 0;
}
标签:运算符,zi,int,每日,11.2,mu,fraction,重载,打卡 From: https://www.cnblogs.com/leapssisbird/p/17347613.html