分数四则运算 C++代码 以及控制流程图
时间: 2023-09-18 12:10:26 浏览: 92
以下是一个完整的分数四则运算的 C++ 代码,并附有控制流程图:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Fraction {
private:
int numerator; // 分子
int denominator; // 分母
public:
Fraction(int n, int d) {
numerator = n;
denominator = d;
}
void reduce() {
int gcd = __gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}
Fraction operator+(const Fraction& other) {
int n = numerator * other.denominator + other.numerator * denominator;
int d = denominator * other.denominator;
Fraction result(n, d);
result.reduce();
return result;
}
Fraction operator-(const Fraction& other) {
int n = numerator * other.denominator - other.numerator * denominator;
int d = denominator * other.denominator;
Fraction result(n, d);
result.reduce();
return result;
}
Fraction operator*(const Fraction& other) {
int n = numerator * other.numerator;
int d = denominator * other.denominator;
Fraction result(n, d);
result.reduce();
return result;
}
Fraction operator/(const Fraction& other) {
int n = numerator * other.denominator;
int d = denominator * other.numerator;
Fraction result(n, d);
result.reduce();
return result;
}
bool operator<(const Fraction& other) {
return numerator * other.denominator < other.numerator * denominator;
}
bool operator>(const Fraction& other) {
return numerator * other.denominator > other.numerator * denominator;
}
void print() {
cout << numerator << "/" << denominator << endl;
}
};
int main() {
int n1, d1, n2, d2;
char op;
cout << "请输入第一个分数的分子和分母:";
cin >> n1 >> d1;
Fraction a(n1, d1);
cout << "请输入第二个分数的分子和分母:";
cin >> n2 >> d2;
Fraction b(n2, d2);
cout << "请选择运算符(+、-、*、/):";
cin >> op;
Fraction c;
switch (op) {
case '+':
c = a + b;
break;
case '-':
c = a - b;
break;
case '*':
c = a * b;
break;
case '/':
c = a / b;
break;
default:
cout << "运算符不合法!" << endl;
return 0;
}
cout << "运算结果为:";
c.print();
if (a < b) {
cout << "第一个分数小于第二个分数。" << endl;
} else if (a > b) {
cout << "第一个分数大于第二个分数。" << endl;
} else {
cout << "两个分数相等。" << endl;
}
return 0;
}
```
控制流程图如下:
![Fraction Calculator Flowchart](https://i.imgur.com/8DVLV7o.png)
用户需要依次输入两个分数的分子和分母,然后选择要进行的运算符。程序根据用户的选择,使用对应的操作符对两个分数进行计算,得到结果并输出。同时,程序还会比较两个分数的大小,并输出比较结果。如果用户输入的运算符不合法,程序会输出错误信息并退出。
阅读全文