【C++】重载+与<<完成约分及输出
By
e2hang
at 2025-05-06 • 0人收藏 • 49人看过
#include <iostream> int min(int a, int b) { return a > b ? b : a; } void yf(int& a, int& b) { bool flag = false; int js = 0; while (flag == false) { for (int i = 2; i < min(a, b);i++) { if (a % i == 0 && b % i == 0) { a /= i; b /= i; js++; } } if (js == 0) flag = true; } std::cout << "Frac Done" << std::endl; } class Fraction { private: int up; int down; public: Fraction() { up = 1; down = 1; } Fraction(int a, int b) { up = a; down = b; } void Fset(int a, int b) { up = a; down = b; } Fraction operator+(Fraction x) { Fraction temp; int up1, down1; up1 = up * x.down + down * x.up; down1 = down * x.down; yf(up1, down1); temp.Fset(up1, down1); return temp; } friend std::ostream& operator<<(std::ostream& os, Fraction x) { os << x.up << "/" << x.down <<std::endl; return os; } ~Fraction() { } }; int main() { Fraction f1(1, 2), f2(2, 3); Fraction f3; f3 = f1 + f2; std::cout << f3 << std::endl; return 0; }
登录后方可回帖