分数的四则运算
- 分数约分
- 分数加法
- 分数减法
- 分数乘法
- 分数除法
- 分数的输出
分数约分
#include <cstdio>
#include <algorithm>
using namespace std;
struct Fraction {//用结构体表示分子和分母
int up, down;
};
int gcd(int a, int b) {//求出最大公约数
if (b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}
//表示分数的时候注意规则
//1.down如果为负数,那么令分子表示负数,分母不表示
//2.如果分数为0,则规定分子为0,分母为1
//3.分子分母必须是最简(同时除以最大公约数)
Fraction reduction(Fraction fraction) {
if (fraction.down < 0) {
fraction.up = -fraction.up;
fraction.down = -fraction.down;
}
if (fraction.up == 0) {
fraction.down = 1;
}
else {
int d = gcd(abs(fraction.up), abs(fraction.down));
fraction.up /= d;
fraction.down /= d;
}
return fraction;
}
int main() {
Fraction fraction;//表示分数
scanf("%d%d", &fraction.up, &fraction.down);//分子和分母
Fraction result = reduction(fraction);
if (result.down == 1) {
printf("%d", result.up);
}
else {
printf("%d %d", result.up, result.down);
}
return 0;
}
分数加法
//加法只是加了一些条件,函数中重新的设置一个分数,进行带入公式
Fraction add(Fraction f1, Fraction f2) {
Fraction result;
result.up = f1.up * f2.down + f2.up * f1.down;
result.down = f1.down * f2.down;
return reduction(result);
}
#include <cstdio>
#include <algorithm>
using namespace std;
struct Fraction {
int up, down;
};
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
Fraction reduction(Fraction fraction) {
if (fraction.down < 0) {
fraction.up = -fraction.up;
fraction.down = -fraction.down;
}
if (fraction.up == 0) {
fraction.down = 1;
} else {
int d = gcd(abs(fraction.up), abs(fraction.down));
fraction.up /= d;
fraction.down /= d;
}
return fraction;
}
Fraction add(Fraction f1, Fraction f2) {
Fraction result;
result.up = f1.up * f2.down + f2.up * f1.down;
result.down = f1.down * f2.down;
return reduction(result);
}
int main() {
Fraction f1, f2;
scanf("%d%d%d%d", &f1.up, &f1.down, &f2.up, &f2.down);
Fraction result = add(f1, f2);
if (result.down == 1) {
printf("%d", result.up);
} else {
printf("%d %d", result.up, result.down);
}
return 0;
}
分数减法
Fraction sub(Fraction f1, Fraction f2) {
Fraction result;
result.up = f1.up * f2.down - f2.up * f1.down;
result.down = f1.down * f2.down;
return reduction(result);
}
分数乘法
Fraction mul(Fraction f1, Fraction f2) {
Fraction result;
result.up = f1.up * f2.up;
result.down = f1.down * f2.down;
return reduction(result);
}
分数除法
Fraction div(Fraction f1, Fraction f2) {
Fraction result;
result.up = f1.up * f2.down;
result.down = f1.down * f2.up;
return reduction(result);
}
分数的输出
int main() {
Fraction f1, f2;
scanf("%d%d%d%d", &f1.up, &f1.down, &f2.up, &f2.down);
Fraction result = add(f1, f2);
if (result.down == 1) {
printf("%d", result.up);
} else {
printf("%d %d", result.up, result.down);
}
return 0;
}