#include<iostream>
#include<algorithm>
using namespace std;
void reduce(int &, int &);//¼ò»¯·ÖÊý£¬Ê¹·Ö×Ó·Öĸͬ³ýÒÔ×î´ó¹«Ô¼Êý
int gcd(int , int );//Çó×î´ó¹«Ô¼Êý
class Fraction{ //·ÖÊýÀà
int up, down;
public:
Fraction(int u, int d){//¹¹Ô캯Êý£¬Ïȼò»¯ºóÔÙ¸³Öµ
reduce(u, d);
up = u; down = d;
}
Fraction(){up = 0; down = 1;reduce(up, down);}//ĬÈϹ¹Ô캯Êý£¬Ä¬ÈÏΪ0£¬Áî·ÖĸΪ1£¬·ÖĸΪ1ÊÓΪÕûÊý
friend Fraction operator +(Fraction , Fraction); //ÉùÃ÷ÓÑÔªº¯Êý£¬²¢ÉùÃ÷ËÄÔòÔËËã
friend Fraction operator -(Fraction, Fraction);
friend Fraction operator *(Fraction, Fraction);
friend Fraction operator /(Fraction, Fraction);
friend ostream & operator <<(ostream &, Fraction );//ÖØÔزÙ×÷·û£¬Ê¹µÃ·½±ãÊäÈëÊä³ö£¬Í¬Ê±ÔÚÊäÈëʱ½øÐмò»¯
friend istream & operator >> (istream &, Fraction &);//×¢Ò⣬ÊäÈëʱÐè¶ÔFraction ÐβÎÒýÓÃ
friend void reduce(int &, int &);//ÓÉÓÚreduce»á·ÃÎÊ˽ÓÐÊý¾Ý³ÉÔ±£¬ÐèÉùÃ÷ΪÓÑÔª
};
void reduce(int & up, int & down){ //ÓÃÓÚ¼ò»¯·ÖÊý
if(down < 0){ //Áî·ÖĸʼÖÕΪÕý£¬·Ö×Ó´øÕý¸ººÅ
up = - up;
down = -down;
}
if(up ==0) down = 1; //µ±·Ö×ÓΪÁãʱ£¬·ÖĸÁîΪ1£¬²¢µ±·ÖĸΪ1ʱ£¬ÊÓΪÕûÊý¡£
else{ //Çó³ö×î´ó¹«Ô¼Êý£¬²¢Ê¹·Ö×Ó·Öĸͬ³ý
int g = gcd(abs(up), abs(down));
up /= g;
down /= g;
}
}
int gcd(int a, int b){//×¢Ò⣬Ҫʹ a¡¢b¾ùΪÕýÊý
return !b? a : gcd(b, a%b);
}
Fraction operator +(Fraction a, Fraction b){
return Fraction(a.up * b.down + b.up * a.down, a.down * b.down);
}
Fraction operator -(Fraction a, Fraction b){
return Fraction(a.up * b.down - b.up * a.down, a.down * b.down);
}
Fraction operator *(Fraction a, Fraction b){
return Fraction(a.up * b.up, a.down * b.down);
}
Fraction operator /(Fraction a, Fraction b){
return Fraction(a.up * b.down, a.down * b.up);
}
ostream & operator <<(ostream & output, Fraction a){
if(a.down == 0) return output <<"INF"<<endl; //·ÖĸΪ0ʱ£¬Êä³öÎÞÇî´ó
else if(a.down == 1) return output << a.up << endl; //·ÖĸΪ1ʱΪÕûÊý£¬Êä³ö·Ö×Ó
if(a.up > a.down) return output << a.up/a.down << " " << abs(a.up) % a.down << "/" << a.down<<endl; //¼Ù·ÖÊýʱ´¦Àí
return output << a.up << "/" << a.down<<endl;//Õæ·ÖÊýÊä³ö
}
istream & operator >> (istream & input, Fraction& a){//ÖØÔزÙ×÷·û£¬ÊäÈëʱ½øÐмò»¯
input >> a.up >>a.down;
reduce(a.up, a.down);//¼ò»¯
return input;
}
int main(){
Fraction a,b;
cin >> a >> b;
cout << a << b;
cout << a + b << a - b << a * b << a / b;
return 0;
}
C++ - 用类表示分数、四则运算、以及输入输出
于 2022-05-14 15:13:07 首次发布