1.分数的表示与分数的运算
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 #include <vector> 5 6 using namespace std ; 7 8 struct Fraction{//分数的定义 9 int up, down ; 10 }; 11 12 int gcd(int a,int b){ 13 return b ? gcd(b,a%b) : a ; 14 } 15 16 Fraction reduction(Fraction ft){//化为最简分数 17 if(ft.down<0){ 18 ft.up = -ft.up ; 19 ft.down = -ft.down ; 20 } 21 if(ft.up == 0){ 22 ft.down = 1 ; 23 }else{ 24 int d = gcd(ft.up,ft.down) ; 25 ft.up /= d ; 26 ft.down /= d ; 27 } 28 return ft ; 29 } 30 31 Fraction add(Fraction ft1,Fraction ft2){//加 32 Fraction res ; 33 res.up = ft1.up*ft2.down + ft1.down*ft2.up ; 34 res.down = ft1.down*ft2.down ; 35 return res ; 36 } 37 38 Fraction sub(Fraction ft1,Fraction ft2){//减 39 Fraction res ; 40 res.up = ft1.up*ft2.down - ft1.down*ft2.up ; 41 res.down = ft1.down*ft2.down ; 42 return res ; 43 } 44 45 Fraction mul(Fraction ft1,Fraction ft2){//乘 46 Fraction res ; 47 res.up = ft1.up*ft2.up ; 48 res.down = ft1.down*ft2.down ; 49 return res ; 50 } 51 52 Fraction div(Fraction ft1,Fraction ft2){//除(需要特判除数是否为0) 53 Fraction res ; 54 res.up = ft1.up*ft2.down ; 55 res.down = ft1.down*ft2.up ; 56 return res ; 57 } 58 59 void ShowResult(Fraction ft){//输出分数 60 ft = reduction(ft) ; 61 if(ft.down == 1){ 62 printf("%lld",ft.up) ; 63 }else if(abs(ft.up>ft.down)){ 64 printf("%d %d/%d",ft.up/ft.down,abs(ft.up)%ft.down,ft.down) ; 65 }else{ 66 printf("%d/%d",ft.up,ft.down) ; 67 } 68 } 69 70 int main(){ 71 72 73 return 0 ; 74 }