分数的乘法
#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 multi(Fraction f1, Fraction f2) { Fraction result; result.up = f1.up * f2.up; 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 = multi(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 divide(Fraction f1, Fraction f2) { Fraction result; result.up = f1.up * f2.down; result.down = f1.down * f2.up; 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 = divide(f1, f2); showResult(res); return 0; }
本模板来自:本文代码模板来自《算法笔记》,书籍如下图所示:
相关博客:分数的加减乘除