Problem Description
编写一个C程序,实现两个分数的加减法
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
代码:(注意如果在eclipse里同包下面写f.java的话,在交代码的时候把class权限改成默认,不然报错)
import java.util.Scanner;
class f {
int fm,fz;
public f(int fz, int fm) {
super();
this.fm = fm;
this.fz = fz;
}
public f() {};
public f add(f x)
{
int z=fm*x.fz + x.fm*fz;
int m=fm*x.fm;
int gys=gys(z,m);
return new f(z/gys,m/gys);
}
public int gys(int a,int b)
{
int r,t;
//System.out.println(a+" "+b);
if(a<b)
{
t=a;
a=b;
b=t;
}
while(b!=0)
{
r=a%b;
a=b;
b=r;
}
return a;
}
public f del(f x)
{
int z=x.fm*fz-fm*x.fz;
int m=fm*x.fm;
int gys=gys(z,m);
//System.out.println(z);//这里记得判断符号,一定要在分子前面
if(z<0)
{
m=-m;
z=-z;
}
return new f(z/gys,m/gys);
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNext())
{
String str=s.nextLine();
char a[]=str.toCharArray();
int az=a[0]-'0';
int am=a[2]-'0';
int bz=a[4]-'0';
int bm=a[6]-'0';
f r1=new f(az, am);
f r2=new f(bz, bm);
f result=new f();
if(a[3]=='+')
{
result=r1.add(r2);
}
else if(a[3]=='-')
{
result=r1.del(r2);
}
if(result.fz%result.fm==0)
System.out.println(result.fz/result.fm);
else System.out.println(result.fz+"/"+result.fm);
}
s.close();
}
}