分数四则运算
Time Limit: 1000 ms
Memory Limit: 65536 KiB
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
Hint
import java.util.Scanner;
class Point {
int a, b;
public Point(int a, int b) {
this.a = a;
this.b = b;
}
public Point add(Point x) {
int d = b * x.b;
int c = a * x.b + b * x.a;
return new Point(c, d);
}
public Point jian(Point x) {
int d = b * x.b;
int c = a * x.b - b * x.a;
return new Point(c, d);
}
public Point mul(Point x) {
int d = b * x.b;
int c = a * x.a;
return new Point(c, d);
}
public Point chu(Point x) {
int d = b * x.a;
int c = a * x.b;
return new Point(c, d);
}
public int gys(int m, int n) {
int r = m;
while (n != 0) {
r = m % n;
m = n;
n = r;
}
return m;
}
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);
str += a1/s+"/"+b1/s;
}
return str;
}
}
public class Main {
public static void main(String[] args) {
Scanner re = new Scanner(System.in);
while(re.hasNext())
{
String s = re.nextLine();
int sum = 0, k = 0, f=0;
int a[] = new int[4];
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i)>'9' || s.charAt(i)<'0')
{
a[k++] = sum;
sum = 0;
if(s.charAt(i)=='+')
f = 1;
else if(s.charAt(i)=='-')
f = 2;
else if(s.charAt(i)=='*')
f = 3;
else if(s.charAt(i)=='/')
f = f;
else f = 4;
}
else
{
sum = sum * 10 + s.charAt(i)-'0';
}
}
a[k] = sum;
Point s1 = new Point(a[0], a[1]);
Point s2 = new Point(a[2], a[3]);
if(f==1)
System.out.println(s1.add(s2));
else if(f==2)
System.out.println(s1.jian(s2));
else if(f==3)
System.out.println(s1.mul(s2));
else System.out.println(s1.chu(s2));
}
re.close();
}
}