用C++编写从键盘上输入两个分数,完成分数的加、减、乘、除运算,并把运算结果打印出来。 例如: 输入:1/8 1/4 输出: 1/8 + 1/4=3/8 1/8 - 1/4=-1/8 1/8×1/4=1/32 1/8÷1/4=1/2
时间: 2024-11-20 12:42:01 浏览: 5
C语言实现并运算(离散数学)
在C++中,你可以使用`cin`从用户处获取输入,然后利用`if-else`语句进行四则运算。这里是一个简单的示例程序:
```cpp
#include <iostream>
using namespace std;
// 定义分数结构体
struct Fraction {
int numerator; // 分子
int denominator; // 分母
// 构造函数
Fraction(int n = 0, int d = 1) : numerator(n), denominator(d) {}
};
// 运算函数
Fraction add(Fraction f1, Fraction f2) {
int commonDenominator = f1.denominator * f2.denominator;
return {f1.numerator * f2.denominator + f2.numerator * f1.denominator, commonDenominator};
}
Fraction subtract(Fraction f1, Fraction f2) {
int commonDenominator = f1.denominator * f2.denominator;
return {f1.numerator * f2.denominator - f2.numerator * f1.denominator, commonDenominator};
}
Fraction multiply(Fraction f1, Fraction f2) {
return {f1.numerator * f2.numerator, f1.denominator * f2.denominator};
}
Fraction divide(Fraction f1, Fraction f2) {
if (f2.denominator == 0)
throw runtime_error("Cannot divide by zero");
return {f1.numerator * f2.denominator, f1.denominator};
}
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;
try {
cout << "Addition: " << f1.numerator << "/" << f1.denominator << " + " << f2.numerator << "/" << f2.denominator << " = " << f1.add(f2).numerator << "/" << f1.add(f2).denominator << endl;
cout << "Subtraction: " << f1.numerator << "/" << f1.denominator << " - " << f2.numerator << "/" << f2.denominator << " = " << f1.subtract(f2).numerator << "/" << f1.subtract(f2).denominator << endl;
cout << "Multiplication: " << f1.numerator << "/" << f1.denominator << " × " << f2.numerator << "/" << f2.denominator << " = " << f1.multiply(f2).numerator << "/" << f1.multiply(f2).denominator << endl;
cout << "Division: " << f1.numerator << "/" << f1.denominator << " ÷ " << f2.numerator << "/" << f2.denominator << " = " << f1.divide(f2).numerator << "/" << f1.divide(f2).denominator << endl;
} catch (const runtime_error& e) {
cerr << "Error: " << e.what() << endl;
}
return 0;
}
```
当你运行这个程序时,它会提示你输入两个分数,然后进行相应的加、减、乘、除操作并显示结果。
阅读全文