写出一段c++代码,用类函数,可以满足将分数(含分子分母)进行加减乘除运算,并且允许键盘输入分数(含分子分母),且输出最后结果。
时间: 2024-11-10 10:13:52 浏览: 16
当然,这里是一个简单的C++程序示例,它定义了一个分数类Fraction,并实现了加、减、乘、除的操作。用户可以通过输入分子和分母来进行操作,并显示结果。
```cpp
#include <iostream>
using namespace std;
class Fraction {
private:
int numerator;
int denominator;
public:
// 构造函数
Fraction(int num = 0, int den = 1) : numerator(num), denominator(den) {}
// 检查分母是否为0
bool isZeroDenominator() const {
return denominator == 0;
}
// 加法
Fraction add(const Fraction& other) const {
int newNumerator = numerator * other.denominator + other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return Fraction(newNumerator, newDenominator);
}
// 减法
Fraction subtract(const Fraction& other) const {
int newNumerator = numerator * other.denominator - other.numerator * denominator;
return Fraction(newNumerator, denominator);
}
// 乘法
Fraction multiply(const Fraction& other) const {
return Fraction(numerator * other.numerator, denominator * other.denominator);
}
// 除法,需要检查除数是否为0
Fraction divide(const Fraction& other) const {
if (other.isZeroDenominator()) {
throw "Cannot divide by zero!";
}
return Fraction(numerator * other.denominator, denominator * other.numerator);
}
// 输出分数
void print() const {
cout << numerator << "/" << denominator << endl;
}
};
int main() {
Fraction f1, f2;
cout << "Enter the first fraction (numerator/denominator): ";
cin >> f1.numerator >> f1.denominator;
cout << "Enter the second fraction (numerator/denominator): ";
cin >> f2.numerator >> f2.denominator;
Fraction result;
cout << "Choose an operation (+, -, *, /): ";
char op;
cin >> op;
switch(op) {
case '+':
result = f1.add(f2);
break;
case '-':
result = f1.subtract(f2);
break;
case '*':
result = f1.multiply(f2);
break;
case '/':
try {
result = f1.divide(f2);
} catch (const char* msg) {
cerr << msg << endl;
return 1; // 错误处理
}
break;
default:
cerr << "Invalid operation!" << endl;
return 1; // 非法操作
}
result.print();
cout << "Result: " << result.print() << endl;
return 0;
}
```
阅读全文