分数的运算符重载,用 c++编写
时间: 2023-06-09 13:03:01 浏览: 108
分数的运算c++
好的,下面是分数的运算符重载代码:
```
#include <stdio.h>
//定义分数类型
typedef struct Fraction {
int numerator; //分子
int denominator; //分母
}fraction;
//计算最大公约数
int gcd(int a, int b) {
if (a % b == 0) {
return b;
} else {
return gcd(b, a % b);
}
}
//分数化简
void reduction(fraction *f) {
int commonDivisor = gcd(f->numerator, f->denominator);
f->numerator /= commonDivisor;
f->denominator /= commonDivisor;
}
//分数相加
fraction operator+(fraction f1, fraction f2) {
fraction sum;
sum.numerator = f1.numerator*f2.denominator + f2.numerator*f1.denominator;
sum.denominator = f1.denominator*f2.denominator;
reduction(&sum);
return sum;
}
//分数相减
fraction operator-(fraction f1, fraction f2) {
fraction difference;
difference.numerator = f1.numerator*f2.denominator - f2.numerator*f1.denominator;
difference.denominator = f1.denominator*f2.denominator;
reduction(&difference);
return difference;
}
//分数相乘
fraction operator*(fraction f1, fraction f2) {
fraction product;
product.numerator = f1.numerator*f2.numerator;
product.denominator = f1.denominator*f2.denominator;
reduction(&product);
return product;
}
//分数相除
fraction operator/(fraction f1, fraction f2) {
fraction quotient;
quotient.numerator = f1.numerator*f2.denominator;
quotient.denominator = f1.denominator*f2.numerator;
reduction("ient);
return quotient;
}
//输出分数
void printFraction(fraction f) {
printf("%d/%d\n", f.numerator, f.denominator);
}
int main() {
fraction f1 = {3, 4};
fraction f2 = {1, 2};
fraction sum = f1 + f2;
printf("f1+f2=");
printFraction(sum);
fraction difference = f1 - f2;
printf("f1-f2=");
printFraction(difference);
fraction product = f1 * f2;
printf("f1*f2=");
printFraction(product);
fraction quotient = f1 / f2;
printf("f1/f2=");
printFraction(quotient);
return 0;
}
```
希望能对你有所帮
阅读全文