分数加减法

Problem Description

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

Input

输入包含多行数据
每行数据是一个字符串,格式是"a/boc/d"。

其中a, b, c, d是一个0-9的整数。o是运算符"+"或者"-"。

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

Output
对于输入数据的每一行输出两个分数的运算结果。
注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数
Sample Input
1/8+3/8
1/4-1/2
1/3-1/3
Sample Output
1/2
-1/4
0
code:
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner reader = new Scanner(System.in);
		
		int a, b, c, d;
		String str;
		char ch;
		while(reader.hasNext())
		{
			str = reader.nextLine();
			a = (int)str.charAt(0) - '0';
			b = (int)str.charAt(2) - '0';
			c = (int)str.charAt(4) - '0';
			d = (int)str.charAt(6) - '0';
			
			ch = str.charAt(3);
			Fenshu fs1 = new Fenshu(a, b);
			Fenshu fs2 = new Fenshu(c, d);
			
			if(ch == '+')
			{
				System.out.println(fs1.add(fs2).toString());
			}
			else if(ch == '-')
			{
				System.out.println(fs1.sub(fs2).toString());
			}
		}
	}

}

class Fenshu
{
	private static final String GCD = null;
	int a, b;
	
	public Fenshu(int a, int b)
	{
		this.a = a;
		this.b = b;
	}
	
	public Fenshu add(Fenshu fs)
	{
		int c = a*fs.b + b*fs.a;
		int d = b*fs.b;
		return new Fenshu(c, d);
	}
	
	public Fenshu sub(Fenshu fs)
	{
		int c = a*fs.b - b*fs.a;
		int d = b*fs.b;
		return new Fenshu(c, d);
	}
	public int guys(int a, int b)
	{
		int m = a;
		int n = b;
		int r = m;
		while(r!=0)
		{
			m = n;
			n = r;
			r = m%n;
		}
		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 = guys(a1, b1);
			a1 = a1/s;
			b1 = b1/s;
			str += (a1+"/"+b1);
		}
		return str;
	}
	
	
	
	
	
	
	
	
	
	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值