分数
分数の掛け算生成
暇つぶしに作ったけど、使うことはなかった・・・・
暇つぶしに作ったけど、使うことはなかった・・・・
#include <cstdio> #include <cstdlib> #include <ctime> int gcd(int x, int y); //greatest common divisor(最大公約数) class Bunsu { public: int bunbo; int bunshi; Bunsu() { bunbo = rand()%30+1; bunshi = rand()%30+1; int div = gcd(bunbo, bunshi); bunbo /= div; bunshi /= div; } Bunsu operator*(const Bunsu& obj) { int div; Bunsu tmp; tmp.bunbo = bunbo * obj.bunbo; tmp.bunshi = bunshi * obj.bunshi; div = gcd(tmp.bunbo, tmp.bunshi); tmp.bunbo /= div; tmp.bunshi /= div; return tmp; } Bunsu operator/(const Bunsu& obj) { Bunsu tmp; tmp.bunshi = obj.bunbo; tmp.bunbo = obj.bunshi; return *this * tmp; } Bunsu& operator=(const Bunsu& obj) { bunbo = obj.bunbo; bunshi = obj.bunshi; return *this; } }; int main() { srand((unsigned int)time(NULL)); for (int i=0;i < 5;i++) { Bunsu a, b, c; c = a * b; printf("%2d %2d %3d\n", a.bunshi, b.bunshi, c.bunshi); printf("-- * -- = ---\n"); printf("%2d %2d %3d\n\n", a.bunbo, b.bunbo, c.bunbo); } return 0; } int gcd(int x, int y){ if (x > y) { if ((x % y) == 0) return y; else return gcd(y, x % y); } else { if ((y % x) == 0) return x; else return gcd(x, y % x); } } 実行結果 9 4 12 -- * -- = --- 7 3 7 5 19 19 -- * -- = --- 28 10 56 26 4 104 -- * -- = --- 19 5 95 7 24 84 -- * -- = --- 2 23 23 4 8 32 -- * -- = --- 3 25 75