设计分数类Fraction,成员数据包括分子Numerator和分母Denominator,类型都是int。 main函数已给定,提交时只需要提交main函数外的代码部分。 #include<iostream> using namespace std; //你提交的代码在这里 int main() { Fraction f1,f2,f3; cin>>f1>>f2; f3=f1+f2; cout<<f1<<" + "<<f2<<" = "<<f3<<endl; f3=f1-f2; cout<<f1<<" - "<<f2<<" = "<<f3<<endl; f3=f1*f2; cout<<f1<<" * "<<f2<<" = "<<f3<<endl; f3=f1/f2; cout<<f1<<" / "<<f2<<" = "<<f3<<endl; return 0; } Input 1行4个整数,前2个整数分别表示第一个分数的分子和分母;后2个整数分别表示第二个分数的分子和分母。分母保证不为0。 Output 按照样例输出格式输出。 Sample Input 1 1 2 3 4 Sample Output 1 1/2 + 3/4 = 5/4 1/2 - 3/4 = -1/4 1/2 * 3/4 = 3/8 1/2 / 3/4 = 2/3 Hint 分数的输出要求: (1)格式:整数/整数 (2)最简形式; (3)分子只能是正整数;
时间: 2023-10-30 11:35:52 浏览: 304
```c++
#include<iostream>
using namespace std;
int gcd(int a, int b) { //辗转相除法求最大公约数
return b == 0 ? a : gcd(b, a % b);
}
class Fraction {
private:
int numerator, denominator; //分子和分母
public:
Fraction(int n = 0, int d = 1) { //构造函数,默认为0/1
numerator = n;
denominator = d;
simplify(); //构造时自动约分
}
friend istream& operator>>(istream& in, Fraction& f) { //输入运算符重载
in >> f.numerator >> f.denominator;
f.simplify(); //读入时自动约分
return in;
}
friend ostream& operator<<(ostream& out, const Fraction& f) { //输出运算符重载
out << f.numerator << '/' << f.denominator;
return out;
}
Fraction operator+(const Fraction& f) const { //加法运算符重载
Fraction res(numerator * f.denominator + f.numerator * denominator, denominator * f.denominator);
return res;
}
Fraction operator-(const Fraction& f) const { //减法运算符重载
Fraction res(numerator * f.denominator - f.numerator * denominator, denominator * f.denominator);
return res;
}
Fraction operator*(const Fraction& f) const { //乘法运算符重载
Fraction res(numerator * f.numerator, denominator * f.denominator);
return res;
}
Fraction operator/(const Fraction& f) const { //除法运算符重载
Fraction res(numerator * f.denominator, denominator * f.numerator);
return res;
}
void simplify() { //约分
int g = gcd(numerator, denominator);
numerator /= g;
denominator /= g;
if (denominator < 0) { //保证分母为正
numerator = -numerator;
denominator = -denominator;
}
}
};
int main() {
Fraction f1, f2, f3;
cin >> f1 >> f2;
f3 = f1 + f2;
cout << f1 << " + " << f2 << " = " << f3 << endl;
f3 = f1 - f2;
cout << f1 << " - " << f2 << " = " << f3 << endl;
f3 = f1 * f2;
cout << f1 << " * " << f2 << " = " << f3 << endl;
f3 = f1 / f2;
cout << f1 << " / " << f2 << " = " << f3 << endl;
return 0;
}
```
阅读全文