当前位置: 首页 > news >正文

分数运算类

分数运算类

定义了分数的四则运算,如果需要处理浮点数,那么需要将函数中的 gcd 运算替换为 fgcd

template<class T> struct Frac {T x, y;Frac() : Frac(0, 1) {}Frac(T x_) : Frac(x_, 1) {}Frac(T x_, T y_) : x(x_), y(y_) {if (y < 0) {y = -y;x = -x;}}constexpr double val() const {return 1. * x / y;}constexpr Frac norm() const { // 调整符号、转化为最简形式T p = gcd(x, y);return {x / p, y / p};}friend constexpr auto &operator<<(ostream &o, const Frac &j) {T p = gcd(j.x, j.y);if (j.y == p) {return o << j.x / p;} else {return o << j.x / p << "/" << j.y / p;}}constexpr Frac &operator/=(const Frac &i) {x *= i.y;y *= i.x;if (y < 0) {x = -x;y = -y;}return *this;}constexpr Frac &operator+=(const Frac &i) { return x = x * i.y + y * i.x, y *= i.y, *this; }constexpr Frac &operator-=(const Frac &i) { return x = x * i.y - y * i.x, y *= i.y, *this; }constexpr Frac &operator*=(const Frac &i) { return x *= i.x, y *= i.y, *this; }friend constexpr Frac operator+(const Frac i, const Frac j) { return i += j; }friend constexpr Frac operator-(const Frac i, const Frac j) { return i -= j; }friend constexpr Frac operator*(const Frac i, const Frac j) { return i *= j; }friend constexpr Frac operator/(const Frac i, const Frac j) { return i /= j; }friend constexpr Frac operator-(const Frac i) { return Frac(-i.x, i.y); }friend constexpr bool operator<(const Frac i, const Frac j) { return i.x * j.y < i.y * j.x; }friend constexpr bool operator>(const Frac i, const Frac j) { return i.x * j.y > i.y * j.x; }friend constexpr bool operator==(const Frac i, const Frac j) { return i.x * j.y == i.y * j.x; }friend constexpr bool operator!=(const Frac i, const Frac j) { return i.x * j.y != i.y * j.x; }
};
http://www.hskmm.com/?act=detail&tid=38040

相关文章:

  • 撸一个功能强大的基于语义的图像检索系统
  • 提交一张 PPT,参与 RTE2025 全球语音智能体云展示
  • 解释 EIP-4337
  • 数论常见结论及例题
  • 求解连续数字的正约数集合——倍数法
  • git回滚代码
  • 组合数
  • q
  • 裴蜀定理
  • 逆元
  • 扩展欧几里得 exgcd
  • 离散对数 bsgs 与 exbsgs
  • 常见数列
  • 20232314 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 【LTDC】LTDC 简介
  • 分类器案例 - -一叶知秋
  • Markdown数学公式 - -一叶知秋
  • 最大流
  • 最小割树 Gomory-Hu Tree
  • 最小割
  • 差分约束
  • 图论常见结论及例题
  • 最长路(topsort+DP算法)
  • 二分图最大匹配
  • 最短路径树(SPT问题)
  • 欧拉路径/欧拉回路 Hierholzers
  • 无源汇点的最小割问题 Stoer–Wagner
  • CF2152G
  • 染色法判定二分图 (dfs算法)
  • 链式前向星建图与搜索