用c++实现带有定义整数类和分数类的分数计算器
时间: 2023-07-10 19:24:22 浏览: 102
好的,我可以为您提供一些基本的代码实现。首先,我们需要定义整数类和分数类。
```c++
class Integer {
private:
int num;
public:
Integer(int n) : num(n) {}
Integer operator+(const Integer& other) const {
return Integer(num + other.num);
}
Integer operator-(const Integer& other) const {
return Integer(num - other.num);
}
Integer operator*(const Integer& other) const {
return Integer(num * other.num);
}
Integer operator/(const Integer& other) const {
return Integer(num / other.num);
}
int getNum() const { return num; }
};
class Fraction {
private:
int numerator;
int denominator;
public:
Fraction(int n, int d) : numerator(n), denominator(d) {}
Fraction operator+(const Fraction& other) const {
int lcm = denominator * other.denominator / gcd(denominator, other.denominator);
int num = numerator * lcm / denominator + other.numerator * lcm / other.denominator;
return Fraction(num, lcm);
}
Fraction operator-(const Fraction& other) const {
int lcm = denominator * other.denominator / gcd(denominator, other.denominator);
int num = numerator * lcm / denominator - other.numerator * lcm / other.denominator;
return Fraction(num, lcm);
}
Fraction operator*(const Fraction& other) const {
return Fraction(numerator * other.numerator, denominator * other.denominator);
}
Fraction operator/(const Fraction& other) const {
return Fraction(numerator * other.denominator, denominator * other.numerator);
}
int getNumerator() const { return numerator; }
int getDenominator() const { return denominator; }
void simplify() {
int g = gcd(numerator, denominator);
numerator /= g;
denominator /= g;
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
};
```
然后我们可以实现一个简单的分数计算器,接受用户输入两个分数和一个操作符,然后计算出结果并输出。
```c++
int main() {
int num1, den1, num2, den2;
char op;
cout << "Please enter two fractions and an operator (+, -, *, /): ";
cin >> num1 >> den1 >> op >> num2 >> den2;
Fraction frac1(num1, den1);
Fraction frac2(num2, den2);
Fraction result;
switch (op) {
case '+':
result = frac1 + frac2;
break;
case '-':
result = frac1 - frac2;
break;
case '*':
result = frac1 * frac2;
break;
case '/':
result = frac1 / frac2;
break;
default:
cout << "Invalid operator!\n";
return 1;
}
result.simplify();
cout << "Result: " << result.getNumerator() << "/" << result.getDenominator() << endl;
return 0;
}
```
这就是一个简单的基于C++的分数计算器的实现。当然,这只是一个简单的示例,您可以根据您的需求进行更多的扩展和改进。
阅读全文