数学:分数的加减乘除
- 分数的表示
- 分数的化简
- 分数的加法
- 分数的减法
- 分数的乘法
- 分数的除法
分数的表示
struct Fraction{ //分数 int up, down; //分子,分母 };
分数的化简
Fraction reduction (Fraction result) { if (result.down < 0) { result.up = - result.up; result.down = - result.down; } if (result.up == 0) result.down = 1; else { int d = gcd(abs(result.up), abs(result.down)); result.up /= d; result.down /= d; } return result; }
分数的加法
#include <iostream> #include <cstdio> #include <algorithm> #include <map> using namespace std; int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } struct Fraction { int up, down; }; Fraction reduction (Fraction result) { if (result.down < 0) { result.up = - result.up; result.down = - result.down; } if (result.up == 0) result.down = 1; else { int d = gcd(abs(result.up), abs(result.down)); result.up /= d; result.down /= d; } return result; } 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); } void showResult (Fraction r) { r = reduction(r); if (r.down == 1) printf("%d", r.up); else if (abs(r.up) > r.down) printf("%d %d/%d", r.up / r.down, abs(r.up) % r.down, r.down); else printf("%d/%d", r.up, r.down); } int main() { Fraction f1, f2; scanf("%d%d", &f1.up, &f1.down); scanf("%d%d", &f2.up, &f2.down); Fraction res = add(f1, f2); showResult(res); return 0; }
分数的减法
#include <iostream> #include <cstdio> #include <algorithm> #include <map> using namespace std; int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } struct Fraction { int up, down; }; Fraction reduction (Fraction result) { if (result.down < 0) { result.up = - result.up; result.down = - result.down; } if (result.up == 0) result.down = 1; else { int d = gcd(abs(result.up), abs(result.down)); result.up /= d; result.down /= d; } return result; } Fraction minu(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); } void showResult (Fraction r) { r = reduction(r); if (r.down == 1) printf("%d", r.up); else if (abs(r.up) > r.down) printf("%d %d/%d", r.up / r.down, abs(r.up) % r.down, r.down); else printf("%d/%d", r.up, r.down); } int main() { Fraction f1, f2; scanf("%d%d", &f1.up, &f1.down); scanf("%d%d", &f2.up, &f2.down); Fraction res = minu(f1, f2); showResult(res); return 0; }