📄 assignment8-1-1_fractioncalculator.cpp
字号:
#include <iostream>
using namespace std;
struct Fraction{
int num;
int den;
};
istream& operator>> (istream& ins, Fraction& f);
ostream& operator<< (ostream& outs, const Fraction& f);
Fraction operator- (const Fraction& f1, const Fraction& f2);
Fraction operator* (const Fraction& f1, const Fraction& f2);
Fraction operator/ (const Fraction& f1, const Fraction& f2);
int main(){
Fraction f, g, h;
cout << "\t\tCalculation Fractor in operator -,*,/" << endl;
cout << "\t\t=====================================" << endl << endl;
cout << "Enter Fraction : ";
cin >> g;
cout << "Enter Fraction : ";
cin >> h;
cout << "-----------------------" << endl;
cout << "The operator (-) = ";
f = g - h;
cout << f << endl;
cout << "The operator (*) = ";
f = g * h;
cout << f << endl;
cout << "The operator (/) = ";
f = g / h;
cout << f << endl;
cout << "-----------------------" << endl;
system("pause");
return 0;
}
istream& operator>> (istream& ins, Fraction& f){
char slash;
ins >> f.num >> slash >> f.den;
return ins;
}
Fraction operator- (const Fraction& f1, const Fraction& f2){
// formula for the sum is a/b - c/d = (ad - bc) / bd;
Fraction the_sum;
the_sum.den = f1.den*f2.den;
the_sum.num = f1.num*f2.den - f1.den*f2.num;
for(int i=the_sum.den;i!=1;i--){
if(the_sum.den%i==0&&the_sum.num%i==0){
the_sum.den=the_sum.den/i;
the_sum.num=the_sum.num/i;
}
}
return the_sum;
}
Fraction operator* (const Fraction& f1, const Fraction& f2){
// formula for the sum is a/b * c/d = ac / bd;
Fraction the_sum;
the_sum.den = f1.den*f2.den;
the_sum.num = f1.num*f2.num;
for(int i=the_sum.den;i!=1;i--){
if(the_sum.den%i==0&&the_sum.num%i==0){
the_sum.den=the_sum.den/i;
the_sum.num=the_sum.num/i;
}
}
return the_sum;
}
Fraction operator/ (const Fraction& f1, const Fraction& f2){
// formula for the sum is (a/b) / (c/d) = (ad / bc);
Fraction the_sum;
the_sum.den = f1.den*f2.num;
the_sum.num = f1.num*f2.den;
for(int i=the_sum.den;i!=1;i--){
if(the_sum.den%i==0&&the_sum.num%i==0){
the_sum.den=the_sum.den/i;
the_sum.num=the_sum.num/i;
}
}
return the_sum;
}
ostream& operator<< (ostream& outs, const Fraction& f){
outs << f.num << '/' << f.den;
return outs;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -