分数四则运算(类)

Problem Description

编写程序,实现两个分数的加减法

Input

输入包含多行数据;

每行数据是一个字符串,格式是"a/boc/d",其中a, b, c, d为数字(每个数字保证为正数并且不存在正号)。o是运算符"+"或者"-","*","\"。

数据以EOF结束,输入数据保证合法。

Output

直接输出结果,并且注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数形式。

Sample Input
1/100+3/100
1/4-1/2
1/3-1/3
1/2*2/1
1/2\1/2
Sample Output
1/25
-1/4
0
1
1

import java.util.Scanner;  
  
class FS{  
    int a;  
    int b;  
      
    public FS(int a, int b) {  
        //super();  
        this.a = a;  
        this.b = b;  
    }  
      
    public FS add(FS fs){  
        int c = a*fs.b+b*fs.a;  
        int d = b*fs.b;  
        return new FS(c, d);  
    }  
      
    public FS sub(FS fs){  
        int c = a*fs.b-b*fs.a;  
        int d = b*fs.b;  
        return new FS(c, d);  
    }  
    public FS mul(FS fs){  
        int c = a*fs.a;  
        int d = b*fs.b;  
        return new FS(c, d);  
    }  
      
    public FS chu(FS fs){  
        int c = a*fs.b;  
        int d = b*fs.a;  
        return new FS(c, d);  
    }   
    public int gys(int m, int n){  
        if(m>n){  
            int t=m;m=n;n=t;  
        }  
        while(m!=0){  
            int t = n%m;  
            n = m;  
            m = t;  
        }  
        return n;  
    }  
      
    public String toString(){  
        String str = "";  
        if(a%b==0){  
            str+=a/b;  
        }  
        else{  
            if(a*b<0){  
                str +="-";  
            }  
            int a1=Math.abs(a);  
            int b1=Math.abs(b);  
            int s = gys(a1, b1);  
            a1 = a1/s;  
            b1 = b1/s;  
            str+=a1+"/"+b1;  
        }  
        return str;  
    }  
}  
public class Main {  
  
    public static void main(String[] args) {  
        //in  
      
        Scanner reader = new Scanner(System.in);  
        while(reader.hasNext()){  
            String str = reader.nextLine();  
            String[] split = str.split("\\D");
            int a=Integer.parseInt(split[0]);
            int b=Integer.parseInt(split[1]);
            int c=Integer.parseInt(split[2]);
            int d=Integer.parseInt(split[3]);
            String[] split1 = str.split("\\d+");
            char op = split1[2].charAt(0);  
              
            FS fs1 = new FS(a, b);  
            FS fs2 = new FS(c, d);  
            if(op=='+'){  
                System.out.println(fs1.add(fs2));  
            }  
            else if(op=='-'){  
                System.out.println(fs1.sub(fs2));  
            }
            else if(op=='*') {
            	System.out.println(fs1.mul(fs2));
            }
            else if(op=='\\') {
            	System.out.println(fs1.chu(fs2));
            }
        }  
    }  
} 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值