NOJ - T020
[編輯] [转简体] (简体译文)
|
作者:huidong
| 分類:【編程】C 程序設計課程
[
3 瀏覽
0 評論
1 贊
1 踩
]
概要
分數的加減乘除運算(四則運算)
正文
分数的加、减、乘、除法
Time Limit: 1000ms, Memory Limit: 10000KB , Accepted: 0, Total Submissions: 0
VIDEO1
Description
输入两个分数,计算它们的加、减、乘、除。
Input
输入为2行,每行分别是分数的分子和分母,采用分数形式(参考输入样例)。输入的数据保证运算结果合理。
Output
输出为4行,分别是两个分数的加、减、乘、除式子和结果,用最简分数形式表示。
Sample Input
2/3 3/7
Sample Output
(2/3)+(3/7)=23/21 (2/3)-(3/7)=5/21 (2/3)*(3/7)=2/7 (2/3)/(3/7)=14/9
© 2002-2012 JDBSoft.
我的代碼:
#include <stdio.h> #include <memory.h> struct Fraction { int a = 0; int b = 0; Fraction() = default; Fraction(int _a, int _b) : a(_a), b(_b) {} Fraction(const Fraction& f) { Copy(f); } void Copy(const Fraction& f) { *this = f; } // 標準化分式,保證負號在分子上 void Normalize() { if ((a < 0 && b < 0) || (a >= 0 && b < 0)) { a = -a; b = -b; } } bool Read() { bool ret = scanf("%d/%d", &a, &b) == 2; Normalize(); return ret; } const char* c_str() { memset(m_str, 0, sizeof(m_str)); sprintf(m_str, "%d/%d", a, b); return m_str; } void Print() { printf(c_str()); } Fraction operator- () { Fraction f = *this; f.a = -f.a; return f; } Fraction operator+ (const Fraction& f) { return Calc(*this, f, ADD); } Fraction operator- (Fraction f) { return Calc(*this, -f, ADD); } Fraction operator* (const Fraction& f) { return Calc(*this, f, MULTIPLY); } Fraction operator/ (Fraction f) { f.a ^= f.b ^= f.a ^= f.b; return Calc(*this, f, MULTIPLY); } private: char m_str[32] = { 0 }; enum TypeCalc { ADD, MULTIPLY }; Fraction Calc(const Fraction& f1, const Fraction& f2, TypeCalc type) { long long _a; if (type == ADD) { _a = (long long)f1.a * f2.b + (long long)f1.b * f2.a; } else if (type == MULTIPLY) { _a = (long long)f1.a * f2.a; } else { return {}; } long long _b = (long long)f1.b * f2.b; long long _g = gcd(_a, _b); if (_g != 0) { Fraction f; f.a = (int)(_a / _g); f.b = (int)(_b / _g); f.Normalize(); return f; } else { return {}; } } long long gcd(long long a, long long b) { if (a == 0 || b == 0) { return a ? a : b; } if (a < b) { a ^= b ^= a ^= b; } long long r = 1; while (r) { r = a % b; a = b; b = r; } return a; } }; int main() { Fraction f1, f2; f1.Read(); f2.Read(); Fraction f_add = f1 + f2; Fraction f_sub = f1 - f2; Fraction f_mul = f1 * f2; Fraction f_div = f1 / f2; const char* bufF1 = f1.c_str(); const char* bufF2 = f2.c_str(); printf("(%s)+(%s)=%s\n", bufF1, bufF2, f_add.c_str()); printf("(%s)-(%s)=%s\n", bufF1, bufF2, f_sub.c_str()); printf("(%s)*(%s)=%s\n", bufF1, bufF2, f_mul.c_str()); printf("(%s)/(%s)=%s\n", bufF1, bufF2, f_div.c_str()); return 0; }