分数四则运算

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

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

Input

输入包含多行数据;

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

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

Output

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

Example Input

1/100+3/100
1/4-1/2
1/3-1/3
1/2*2/1
1/2\1/2

Example Output

1/25
-1/4
0
1
1

生敲代码200行

 

import java.util.*;

public class Main {
public static int gcd(int a, int b)
{
return b==0?a:gcd(b, a%b);
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while(cin.hasNext())
{
String str;
str = cin.nextLine();
int s1, s2, t1, t2;
int i;
s1 = 0;
char s = '+';
int n = str.length();
for(i = 0; i < n; i++)
{
char e;
e = str.charAt(i);
if(e == '/')
{
i++;
break;
}
else
{
s1 = s1*10;
s1 = s1 + e - '0';
}
}
s2 = 0;
for(; i < n; i++)
{
char e;
e = str.charAt(i);
if(e == '*' || e=='-'||e=='+'||e=='\\')
{
i++;
s = e;
break;
}
else
{
s2 = s2*10;
s2 = s2 + e - '0';
}
}
t1 = 0;
for(; i < n; i++)
{
char e;
e = str.charAt(i);
if(e == '/')
{
i++;
break;
}
else
{
t1 = t1*10;
t1 = t1 + e - '0';
}
}
t2 = 0;
for(; i < n; i++)
{
char e;
e = str.charAt(i);
t2 = t2*10;
t2 = t2 + e - '0';
}
//System.out.println(s1+" "+s2+" "+t1+" "+t2);
if(s == '+')
{
s1 = s1*t2+s2*t1;
s2 = s2*t2;
int t = gcd(s1, s2);
if(s2 == 1)
{
System.out.println(s1);
}
else if(t == 1)
{
System.out.println(s1+"/"+s2);
}
else
{
s1 = s1/t;
s2 = s2/t;
if(s2 == 1)
{
System.out.println(s1);
}
else
{
System.out.println(s1+"/"+s2);
}
}
}
else if(s == '-')
{
s1 = s1*t2-s2*t1;
s2 = s2*t2;
int f = 1;
if(s1 < 0)
{
s1 = -s1;
f = -1;
}
int t = gcd(s1, s2);
s1 = s1*f;
if(s2 == 1)
{
System.out.println(s1);
}
else if(t == 1)
{
System.out.println(s1+"/"+s2);
}
else
{
s1 = s1/t;
s2 = s2/t;
if(s2 == 1)
{
System.out.println(s1);
}
else
{
System.out.println(s1+"/"+s2);
}
}
}
else if(s == '*')
{
s1 = s1*t1;
s2 = s2*t2;
int t = gcd(s1, s2);
if(s2 == 1)
{
System.out.println(s1);
}
else if(t == 1)
{
System.out.println(s1+"/"+s2);
}
else
{
s1 = s1/t;
s2 = s2/t;
if(s2 == 1)
{
System.out.println(s1);
}
else
{
System.out.println(s1+"/"+s2);
}
}
}
else
{
s1 = s1*t2;
s2 = s2*t1;
int t = gcd(s1, s2);
if(s2 == 1)
{
System.out.println(s1);
}
else if(t == 1)
{
System.out.println(s1+"/"+s2);
}
else
{

s1 = s1/t;
s2 = s2/t;
if(s2 == 1)
{
System.out.println(s1);
}
else
{
System.out.println(s1+"/"+s2);
}
}
}
}
}
}