分数四则运算

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
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 = 0;
		while(reader.hasNext())
		{
			str = reader.nextLine();
			for(int i = 0;i<str.length();i++)
			{
				if(str.charAt(i) == '+'||str.charAt(i) == '-'||str.charAt(i) == '*'||str.charAt(i) == '\\')
					{
							ch = str.charAt(i);
							break;
					}
			}
			String str2[] = str.split("\\+|-|\\*|/|\\\\");
			a = Integer.parseInt(str2[0]);
			b = Integer.parseInt(str2[1]);
			c = Integer.parseInt(str2[2]);
			d = Integer.parseInt(str2[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());
			}
			else if(ch == '*')
			{
				System.out.println(fs1.cheng(fs2).toString());
			}
			else if(ch == '\\')
			{
				System.out.println(fs1.chu(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 Fenshu cheng(Fenshu fs)
	{
		return new Fenshu(a*fs.a, b*fs.b);
	}
	public Fenshu chu(Fenshu fs)
	{
		return new Fenshu(a*fs.b, b*fs.a);
	}
	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、付费专栏及课程。

余额充值