Java sdut acm 2253 分数加减法

题目链接:点击打开链接

分数加减法
Time Limit: 1000MS Memory Limit: 65536KB 
Submit Statistic Discuss 
Problem Description
编写一个C程序,实现两个分数的加减法


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


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


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


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


代码实现:

import java.util.Scanner;

class Fenshi {
	int fz;
	int fm;

	public Fenshi() {
	}

	public Fenshi(int fz, int fm) {
		this.fz = fz;
		this.fm = fm;
	}

	public Fenshi add(Fenshi fs) {
		int newfz = fz * fs.fm + fm * fs.fz;
		int newfm = fm * fs.fm;
		return new Fenshi(newfz,newfm);

	}

	public Fenshi sub(Fenshi fs) {
		int newfz = fz * fs.fm - fm * fs.fz;
		int newfm = fm * fs.fm;
		return new Fenshi(newfz,newfm);
	}
}

public class Main {
	static int gcd(int a, int b) {
		if (b == 0)
			return a;
		else
			return gcd(b, a % b);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		while (input.hasNext()) {
			String str = input.next();
			char[] array = str.toCharArray();
			int a = array[0] - '0';
			int b = array[2] - '0';
			int c = array[4] - '0';
			int d = array[6] - '0';
			Fenshi fs1 = new Fenshi(a, b);
			Fenshi fs2 = new Fenshi(c, d);
			Fenshi result = new Fenshi();
			if (array[3] == '+')
				result = fs1.add(fs2);
			else if (array[3] == '-')
				result = fs1.sub(fs2);
			if (result.fz % result.fm == 0 || result.fz == 0)
				System.out.println(result.fz / result.fm);
			else {
				int g = gcd(Math.abs(result.fz), result.fm);
				System.out.printf("%d/%d\n", result.fz / g, result.fm / g);
			}
		}
	}
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值